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?