Here is my attempt at doing it /* function must be implemented recursively. You
ID: 3546643 • Letter: H
Question
Here is my attempt at doing it
/* function must be implemented recursively. You may not use any
loops in this file.
*/
/* Return the number of times `item` is found in `array`.
`n` corresponds to the number of elements in `array`.
*/
template <class T>
int count(const T *array, int n, T item) {
// TODO: Implement this function.
int occur=0;
if(n){
if(item==array[n])
occur=1;
else
occur+=count(array+1,n-1,item);
}
return occur;
}
Explanation / Answer
please rate - thanks
#include <iostream>
using namespace std;
/* function must be implemented recursively. You may not use any
loops in this file.
*/
/* Return the number of times `item` is found in `array`.
`n` corresponds to the number of elements in `array`.
*/
template <class T>
int count(const T *array, int n, T item) {
// TODO: Implement this function.
if(n==0){return 0;
}
else
if(*array==item)
return 1+count(array+1,n-1,item);
else
return count(array+1,n-1,item);
}
int main()
{int array[]={1,2,3,3,4,5,3};
char c[]={'a','b','c','d','d','e'};
cout<<count(array,7,5)<<endl;
cout<<count(array,7,3)<<endl;
cout<<count(c,6,'d')<<endl;
cout<<count(c,6,'a')<<endl;
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.