Can someone explain how the output is what it is?

Sep 27, 2021 at 9:15pm
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 Sep 27, 2021 at 9:16pm
Sep 27, 2021 at 9:49pm
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 Sep 27, 2021 at 9:51pm
Sep 28, 2021 at 3:07am
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?
Sep 28, 2021 at 4:08am
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.