here's a problem that I can't figure it out
The program should count the repetition of a number but when I run the program it seems that the function calls itself once not until the array ends as it's required
any help?
This is the code please have a look :)
#include <stdio.h>
int count(int arr[],int counter,int size, int num,int i) {
if (size != 0) {
while (i<10) {
if (arr[size - i] == num) {
count(arr, size, counter++, num, i++);
}
else
return counter;
}
}
int main() {
int result,n,i=1;
int arr[] = {1,2,2,3,7,2,5,3,8,7};
scanf("%d", &n);
result=count(arr, 0,10,n,i);
printf("%d", result);
return 0;
}
This might be help you:
#include <stdio.h>
int count(int arr[],int counter,int size, int num,int i) {
if (size != 0) {
for (;i<size;i++) {
if (arr[i] == num) {
counter++;
}
}
}
return counter;
}
int main() {
int result,n,i=0,countt=0;
int arr[] = {1,2,2,3,7,2,5,3,8,7};
scanf("%d", &n);
result=count(arr, countt,10,n,i);
printf("%d", result);
return 0;
}
If you are using recursion to iterate over the input array, you should not loop over the same array in the recursive function.
Couple of problem in your code:
Function is not returning anything when this if condition results in false:
if (size != 0) {
Compiler must be giving warning on this regards.
Here, you are not ignoring the return value of count():
count(arr, size, counter++, num, i++);
Your recursive function count() is supposed to return the frequency of num. So, you should receive the value returned by count() as it accumulate the frequency of num during recursive call.
This can be easily solved using recursion. You can do:
#include <stdio.h>
int count (int *arr, int counter, int size, int num) {
// terminating condition
if (size <= 0) {
return counter;
}
// check the current processing number
if (*arr == num) {
counter++;
}
// recursive call to process next number
return count (arr + 1, counter, size - 1, num);
}
int main() {
int arr[] = {1,2,2,3,7,2,5,3,8,7};
int result, n;
printf ("Enter a number:\n");
scanf ("%d", &n);
result = count(arr, 0, sizeof (arr)/sizeof (arr[0]), n);
printf ("Frequency of %d is %d\n", n, result);
return 0;
}
Additional:
Do not hardcode the size of an array. You can use sizeof operator to get an array size at compile time, like this:
sizeof (arr)/sizeof (arr[0])
Make yourself aware of tail recursion, if you are not:
A function call is said to be tail recursive if there is nothing to do after the function returns except return its value. A tail recursive function can be easily transformed into an iterative one and hence compilers can also optimize the code for such functions by eliminating the recursion, that means, tail recursive calls run in constant stack space, i.e. they don't need to create new stack frames when they recursively call themselves. Check following for better idea:
How exactly does tail recursion work?
Related
Problem: A program to count the number of times a number repeats in an array using recursion.
What I've done: I've tried every way I know, I've gone with an output array for storing indices of the number, and just ++ to another number on finding a match to current number. Nothing seems to work, it's one error or another (I'm a noob). I tried looking for solutions online, found solutions on 3-4 websites but had no clue what was going on.
Here's the code:
#include <iostream>
using namespace std;
int ind(int a[], int size, int x){
int j;
if(size == 0){
return 0;}
else if (a[0]==x){
j++;
return j;
}
reind(a++,size—,x);
}
int main(){
int a[5] = {1,2,3,3,5};
ind(a, 5, 3);
}
Edit: That "reind" was a typo, I still get segmentation fault with "ind". Sorry for that.
There are quite a number of mistakes in this code:
j is uninitialized, and even if it weren’t, you are not using the value of j correctly.
There is a missing return on the recursive call to ind() (is that what the re was supposed to be?).
You are passing the original values of a and size to the recursive ind(), causing an endless loop. You are using the post-increment and post-decrement operators, which return the original values, not the new values. You would need to use the pre-increment and pre-decrement operators instead. Which is a bit overkill in this situation, as you don’t use the variables anymore after they are adjusted. So simple addition and subtraction operators can be used instead.
main() is ignoring the return value of ind().
Try this instead:
#include <iostream>
using namespace std;
int ind(int a[], int size, int x){
int j = 0;
if (size == 0){
return 0;
}
if (a[0] == x){
++j;
}
return j + ind(a+1, size-1, x);
}
int main(){
int a[5] = {1, 2, 3, 3, 5};
cout << ind(a, 5, 3);
}
Live Demo
That being said, j and the 2nd if can be eliminated completely:
int ind(int a[], int size, int x){
if (size == 0){
return 0;
}
return (a[0] == x ? 1 : 0) + ind(a+1, size-1, x);
}
Or:
int ind(int a[], int size, int x){
if (size == 0){
return 0;
}
return int(a[0] == x) + ind(a+1, size-1, x);
}
I'm testing a recursive function that returns the number of occurrence of a given number in an array. I get an unexpected result when I run the code.
#include <iostream.h>
int Occurence(int A[], int size, int n)
{
static int occur=0;
if(size == 0)
{
int occur2 = (int) occur;
return occur2;
}
else
{
if ( n == A[size-1])
occur++;
Occurence(A, size-1, n);
}
}
int main()
{
int A[] = {1,3,2,5,1,2, 3, 7,7, 8,8, 4, 6, 9,9, 0};
int size = sizeof(A)/sizeof(A[0]);
int n;
cout<< "Enter Number to Find : ";
cin >>n;
cout<<endl;
cout<<"Number of Occurence of "<< n << " is :"<< Occurence(A, size, n)<<endl;
return 0;
}
You are missing a return at the end of your function. If size is not 0 then the behaviour of your function is undefined. Adding the return should make it work:
int Occurence(int A[], int size, int n)
{
static int occur=0;
if(size == 0)
{
int occur2 = (int) occur;
return occur2;
}
else
{
if ( n == A[size-1])
occur++;
return Occurence(A, size-1, n);
}
}
Recursion is a very strange way to implement this problem so I assume this is some toy example to demonstrate how recursion works. Even if this is the case you really shouldn't be using a static variable in your implementation. Just make each call return the current sum instead:
int Occurence(int A[], int size, int n)
{
if(size == 0)
{
return 0;
}
else
{
return (n == A[size-1] ? 1 : 0) + Occurence(A, size-1, n);
}
}
This version will return the correct result when called multiple times whereas your original would add to the previous count each time.
In real code simply do:
#include <algorithm>
int Occurence(int A[], int size, int n)
{
return std::count(A, A+size, n);
}
There are some compilation problems in your code. First of all, in C++, the standard library files usually don't have an extension in the filename. So, including <iostream.h> is wrong. You should include <iostream>.
Other problem with your code is that you are using cout and cin without specifying their namespaces. So, instead of using cout and cin directly, use std::cout and std::cin or declare use namespace std after your includes.
EDIT: as Thomas Matthews pointed out, prefer using std::cout and std::cin over using namespace std.
I have used this function to find the maximum element
It works for some cases but it got wrong place in other cases and this is the case i call function with.
int maxElement=maxi(names,noOfTeams,0,1,sum,0)
this is the function :
int maxi(string names[],int sizee,int prev,int next,int scores[],int maxx)
{
if (sizee ==1)return 0;
if (scores[maxx]<scores[next]) maxx=next;
if ((next+1)==sizee)return maxx;
else return maxi(names,sizee,prev+1,next+1,scores,maxx);
}
You have couple of errors in your function.
The line
else if (scores[prev]<scores[next])maxx=next;
needs to be
else if (scores[maxx]<scores[next])maxx=next;
// ^^^^
You are missing a return in the recursive call. Instead of
else maxi(names,sizee,prev+1,next+1,scores,maxx);
it needs to be
else
return maxi(names,sizee,prev+1,next+1,scores,maxx);
Also, the function can be simplified.
The argument name is not used at all. It can be removed.
The argument prev can be removed too.
Couple of the checks you have can be combined into one.
You don't need a chain of if-else-else statements.
Here's a simplified version.
int maxi(int sizee, int next, int scores[], int maxx)
{
if ( sizee == next )
return maxx;
if (scores[maxx] < scores[next])
maxx=next;
return maxi(sizee, next+1, scores, maxx);
}
More importantly, it will be better to have an overload of the function:
int maxi(int sizee, int scores[]);
That should be the user facing function. The implementation of the user facing function can use the recursive function as an implementation detail.
int maxi(int sizee, int scores[])
{
return maxi(sizee, 0, scores, 0);
}
See it working at http://ideone.com/chvtPA.
Below could be a better approach:
Go through each element of the array, till there are elements left in the array which will be the base case.
Then in each function call check whether element at current index is greater than the element found at maxIndex if so update the max index and check for next array element by calling function again and so on.
Please find code below for both finding max element and max index recursively:
#include <iostream>
using namespace std;
int findMax(int arr[], int size,int index, int max);
int findMaxIndex(int arr[], int size,int index, int maxIndex);
int main()
{
int arr[] = {5,2,8,1,4};
int len = sizeof(arr) / sizeof(int);
cout << "Max is: " << findMax(arr, len, 0, arr[0]) << endl;
cout << "Max Index is: " << findMaxIndex(arr, len, 0, 0) << endl;
return 0;
}
int findMax(int arr[], int size, int index, int max)
{
if (index == size)
return max;
if (arr[index] > max)
max = arr[index];
return findMax(arr, size, index + 1, max);
}
int findMaxIndex(int arr[], int size, int index, int maxIndex)
{
if (index == size)
return maxIndex;
if (arr[index] > arr[maxIndex])
maxIndex = index;
return findMaxIndex(arr, size, index + 1, maxIndex);
}
You need to compare scores[maxx] with scores[next], aslo you dont need prev
Change your function to
int maxi(string names[],int sizee,int next,int scores[],int maxx)
{
if (sizee ==1)
return 0;
if (scores[maxx]<scores[next])
maxx=next;
if ((next+1)==sizee)
return maxx;
return maxi(names,sizee,next+1,scores,maxx);
//You need to return, else the function will be called but that
// value wont be returned.
}
#include <iostream>
#include <cstdlib>
using std:: cin;
using std:: cout;
using std:: endl;
const int N=10;
void readarray(int array[], int N);
int find_num(int array[], int size);
int main ()
{
int array[N];
readarray (array, N);
cout << find_num(array, N);
return EXIT_SUCCESS;
}
void readarray(int array[], int N)
// this function is for inputting an array also using recursion
{
int i=0;
if (i < N)
{
cin >> array[i];
readarray(array+1, N-1);
}
}
int find_num(int array[], int size)
// this function is for checking if a number is in the array that
// was inputted
{
int n;
cin >> n;
if (n==array[0])
return 1;
else if (n!=array[0]){
find_num(array+1, size-1);
return 1;
}
else return 0;
}
Obviously, the whole point of the program is to only use recursion. I am having a problem with the the second function which is supposed to be checking if a number is found in the array or not. If the number has been found in the array then the output will be 1 if not then it should be 0. The problem is, it seems like it is taking more inputs than it should be and always outputs the number 1 (regardless if the number was found or not). I believe I am missing a small step. I do also want to ask if the void function is correct as well (seems like its working fine to me). thanks.
There are two termination criteria for your recursive function.
If you reache the end of the array, you haven't found the number n and return 0.
If you found the number n return 1.
If you not reache the end of the array and the number was not found, call your function rcursive, get the result and return it.
Apart from this the number you are searching for has to be an input to your function find_num. You don`t want to ask for a number again and again.
int find_num(int n, int array[], int size)
{
if ( size == 0 )
return 0; // end of array, n was not found
if ( n == array[0] )
return 1; // n was found
return find_num( n, array+1, size-1 ); // test next element of array
}
void readarray(int array[], int N)
{
if ( N > 0 )
{
cin >> array[0];
readarray( array+1, N-1 );
}
}
int main ()
{
int array[N];
readarray( array, N );
int n;
cin >> n;
cout << find_num( n, array, N );
return EXIT_SUCCESS;
}
#include <cstdio>
#include <ctime>
int populate_primes(int array[])
{
const int max = 1000000;
char numbers[max+1];
int count=1;
array[0]=2;
for(int i=max;i>0;i-=2)numbers[i]=0;
for(int i=max-1;i>0;i-=2)numbers[i]=1;
int i;
for(i=3;i*i<=max;i+=2){
if(numbers[i]){
for(int j=i*i;j<max+1;j+=i)numbers[j]=0; array[count++]=i;
}
}
int limit = max/2;
for(;i<limit;i++) if(numbers[i])array[count++]=i;
return count;
}
int factorize(int number,int array[])
{
int i=0,factor=1;
while(number>0){
if(number%array[i]==0){
factor++;
while(number%array[i]==0)number/=array[i];
}
i++;
}
printf("%d\n",factor);
return factor;
}
int main()
{
int primes[42000];
const int max = 1000000;
int factors[max+1];
clock_t start = clock();
int size = populate_primes(primes);
factorize(1000,primes);
printf("Execution time:\t%lf\n",(double)(clock()-start)/CLOCKS_PER_SEC);
return 0;
}
I am trying to find the no. of factors using simple algo. The populate primes part is running okay , but the factorize part does not execute and gives the floating point exception error.
Please see the code and tell my mistake.
In your factorize method you access array[0], because the initial value of i is 0.
This array is the primes array which is populated by populate_primes. But populates prime doesn't write to primes[0], since the initial value of count is 1.
Thus the first element is not initialized and you probably get a div by 0 error.
You need to pass the size which you got from populate to factorize.
factorize(int number, int array[], int size);
problem is your array[] is not fully loaded, it is loaded only till size variable. So you may want to check for that.
Also the logic inside factorize is wrong. You need to check (number > 1) rather than (number >0).
Try with the function below to see some problems:
#define MAX_PRIMES 42000
int factorize(int number,int array[])
{
int i=0,factor=1;
for (i=0; number>0 && i< MAX_PRIMES; i++){
if (array[i] == 0 || array[i] == 1) {
printf("Error: array[%d] = %d\n", i, array[i]);
} else {
if(number%array[i]==0){
factor++;
while(number%array[i]==0 && number>0) {
printf("%d %d\n", number, array[i]);
number/=array[i];
}
}
}
}
printf("%d\n",factor);
return factor;
}