Number of times number appears in an array
I found an exercise in a C++ book that says "Write a function that will
count the number of times a number appears in an array.". Everything is
fine, the program is working. But the exercise also says that the function
should be recursive.
How can I make a recursive function working like this?
#include <iostream>
int count(int number, int array[], int length)
{
int counter = 0;
for(int i = 0; i < length; i++)
if(array[i] == number)
counter++;
return counter;
}
int main()
{
int numbers[10] = {3,4,1,2,4,5,6,5,4,5};
int number_to_search = 5;
std::cout << number_to_search << " appears " <<count(number_to_search,
numbers, 10) << " times in the array.";
return 0;
}
No comments:
Post a Comment