Iteration and Recursion yielding different output | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Iteration and Recursion yielding different output

Can some assist in debugging this error. #include <iostream> using namespace std; /* //Iterative code which works as desired int question (int a , int b){ while ( a > 0) { b = a+b ; a--; } return b ; }*/ //Recursive version int question(int a, int b){ if (a>0){ b=a+b; a--; question(a, b); } return b ; } int main(){ cout<<question(6,12); return 0; } //Thanks

24th Dec 2016, 9:10 PM
Tomiwa Ogunbamowo
Tomiwa Ogunbamowo - avatar
3 Answers
+ 2
In the iterative version a and b is the same for each iteration. In the recursive version a and b is uniqu for each call to the function. you have to use pointers as arguments to the function for your code to work.
24th Dec 2016, 9:28 PM
Mattias Eriksson
Mattias Eriksson - avatar
+ 1
//use this in the recursive version: int question(int a, int b){ if (a>0){ b = a + question(a-1,b); } return 0; }
24th Dec 2016, 9:23 PM
amin khozaei
amin khozaei - avatar
0
thanks Amin!
24th Dec 2016, 9:28 PM
Tomiwa Ogunbamowo
Tomiwa Ogunbamowo - avatar