#include<iostream>
usingnamespace std;
void fun(int x) {
if(x > 1) {
cout << --x << " ";
fun(--x);
cout << x << " ";
}
}
int main() {
int a = 5;
fun(a);
return 0;
}
Which gives me an output of 4 2 1 3, but I am not sure why, its the correct answer but Im trying to understand how its getting those numbers from just 5, can someone explain it to me if possible?
well, you call it with 5, it is -- to 4 and printed. Then you call it with --4, which is 3.
fun called with 3 is > 1, so --3 is 2, print 2, .... can you follow how that happens and continue from here?
maybe a better question is, can you follow a more normal recursion function through? Do you understand how the inefficient recursive factorial works?