Can someone explain how the output is what it is?

So I have the this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>​
using namespace 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?
Last edited on
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?
Last edited on
Oh okay I understand that but how do you get 3 in the end? Is it from when you get --4 and it just saves it or something?
Add print statements and you will see it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
using namespace std;

void fun(int x) {

  if(x > 1) {

    cout << "printing x-1 "<< --x << " " << endl;
    cout <<"calling fun " << x-1 << endl;
    fun(--x);

    cout <<"printing x " << x << endl;

  }
}

 

int main() {

  int a = 5;

  fun(a);

  return 0;
}

Topic archived. No new replies allowed.