+ 8

Trying to rewrite a programm using recursion.

Hello sololearners and sologurus! I want to rewrite a programm using recursion and I can't really wrap my mind about this concept and how should I use it in this case. I know that I must declare a function and this function should call itself. Any help is welcomed. I have this programm: // frequency of a nr in a given array #include <iostream> using namespace std; int main(){ int a, arr[5], counter=0, i; cout<<"Enter a:" <<endl; cin>>a; cout<<"Enter elements of the array: "<<endl; for(i=0;i<5;i++){ cin>>arr[i]; } for(i=0;i<5;i++){ if(a==arr[i]) counter++; } cout<<"We have nr "<<a<<": "<<counter<<" time(s) in the array."<<endl; return 0; } And I want to rewrite it using recursion.

5th Mar 2017, 11:11 AM
Elena
Elena - avatar
2 Answers
+ 5
#include <iostream> using namespace std; int f(int val, int i = 1) { int a; cin >> a; return (a == val) + ( i < 5? f(val, i+1): 0); } int main() { int val; cout << "Enter value: "; cin >> val; cout << "Enter 5 elements of the array: " << endl; int count = f(val); cout << "We have number " << val << ": " << count << " time(s) in the array." << endl; }
5th Mar 2017, 1:23 PM
SUPER_S
SUPER_S - avatar
+ 1
#include <iostream> using namespace std; int RecursiveCount(int array[], int value, int index, int size) { if(index == size-1) return array[index] == value ? 1 : 0; if(array[index] == value) return 1 + RecursiveCount(array,value,index+1,size); else return 0 + RecursiveCount(array,value,index+1,size); } int main() { int a[10], value, sizeOfArray; cout<<"Enter desired value"; cin>>value; cout<<endl<<"Enter the size of array(between 1 and 10)"; cin>>sizeOfArray; if(sizeOfArray < 1 || sizeOfArray > 10) { cout<<endl<<"Wrong size of array!" ; return -1; } cout<<endl<<"Enter the elements of the array:"; for(int i=0; i<sizeOfArray; i++) cin>>a[i]; int count = RecursiveCount(a,value,0,sizeOfArray); cout<<endl<<endl<<"We have a number of "<<count<<" appearances of value "<< value<<" in the given array"<<endl; return 0; } I made the program run for any array with a size between 1 and 10. Using the recursive function, I go through all numbers from array. The stop condition consists in arriving at the last nr from array. if the last nr from array is equal with my desired value, i return 1, else i return 0. For the rest of array, I return 0 + f(nextElement) if nr[i]!= value and 1 + f(nextElement) if nr[i]==value. I hope the code is written clearly enough and easy to understand :)
5th Mar 2017, 7:16 PM
Mihai Alex
Mihai Alex - avatar