You are using a version without Ads of this website. Please, consider donating:

### Recursion Function

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.

 ``12345678910111213141516171819`` ``````#include using namespace std; int tryit(int i) { int j=4; int k=1; if(i > 0) return tryit(i-1) * j + k; else return 1; } int main() { int i = 4; int x; x = tryit(i); cout << "x= " << x << endl; return 0; }``````
"Run" your program on paper. Until tryit(0) is called, it keeps calling itself. Look at this little stack trace I made.

 ``` tryit(0) = 1 tryit(1) = (1) * 4 + 1 = 5 tryit(2) = (5) * 4 + 1 = 21 tryit(3) = (21) * 4 + 1 = 85 tryit(4) = (85) * 4 + 1 = 341 ```

The numbers in parenthesis are the return values of the recursive call to tryit(). What exactly are you trying to do?
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)
I thought the return 1 was to break the loop after once i = 0?
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().
Topic archived. No new replies allowed.