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.

6th May 2023, 12:18 PM
DevAbdul
DevAbdul - avatar
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
6th May 2023, 3:35 PM
Orin Cook
Orin Cook - avatar
+ 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
6th May 2023, 1:19 PM
Orin Cook
Orin Cook - avatar
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?
6th May 2023, 1:52 PM
DevAbdul
DevAbdul - avatar
0
Thank you Orin👍
7th May 2023, 5:17 PM
DevAbdul
DevAbdul - avatar