0
Understanding Recursion in C++đ€đ€
Please can somehow explain how the following recursive function works, and why it outputs 01234 when 5 is passed as argument? void calc(int x){ if(x > 0){ calc(--x); cout << x; }else{ return; } } int main() { calc(5); Thanks.
4 Answers
+ 2
Well, both are true. But it's important to understand exactly why. Here's what the computer does:
calc(5):
x > 0, so --x and calc(4):
x> 0, so --x and calc(3):
x > 0, so --x and calc(2):
x > 0, so --x and calc(1):
x > 0, so --x and calc(0):
x !> 0, so return to calc(1);
cout x of calc(1), which is 0; done with calc(1)
cout x of calc(2), which is 1; done with calc(2)
cout x of calc(3), which is 2; done with calc(3)
cout x of calc(4), which is 3; done with calc(4)
cout x of calc(5), which is 4; done with calc(5)
done with main, exit
+ 1
because the recursive call comes before the cout, it'll finish the next calc() in line before it goes on to the cout step.
So when it does get to x=0, the if check fails, cout(0) returns, and it goes back to finish calc(1), where it prints x (which is 0 because of the --), and then with calc(1) done it goes back to finish calc(2), and so on
0
Thanks Orin Cook for the answer, but I still don't get itđ
, do you mean the recursive call is evaluated untill it is false, then the function starts printing the values from cout in a reversed order?
0
Thank you Orinđ