+ 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
3 Respuestas
+ 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.
+ 1
//use this in the recursive version:
int question(int a, int b){
if (a>0){
b = a + question(a-1,b);
}
return 0;
}
0
thanks Amin!