I've looked at some tutorials online but I still can't figure out how this is evaluating to 341. If the first value is 4 and is passed to the function then the first if is true so it returns 4-1 * 4 + 1, that's all I can get from this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int tryit(int i)
{
int j=4;
int k=1;
if(i > 0)
return tryit(i-1) * j + k;
elsereturn 1;
}
int main()
{
int i = 4;
int x;
x = tryit(i);
cout << "x= " << x << endl;
return 0;
}
this is a sample question for my exam, but we did not do anything with recursion during the semester. I think what was confusing me was the tryit(i - 1)
Once i = 0, it stops calling itself (that is why there is no tryit(-1) being called), but still has to go back up the stack and finish all the other calls to tryit().