recursion and a true beginner

Hello there, first message as you can guess, and with it a really basic question comes! I've started learning about c++ just a few days ago, and now I have a little doubt.

The following code generates the factorial of the number given by the user, and I wonder why it works so well!
In other words: doesn't the recurse function return x to main the number of times needed to the if statement to become false? Shouldn't main display something until the true factorial is finally shown?

Thanks in advance for your patience!

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

int x=1;
  
int recurse(int c) {

  if(c) {
     x=x*c;
     recurse(c-1);
  }
  return x;
}

int main() {

  int k;
  cin>>k;
  cout<<recurse(k);
  
  return 0;
}
This is actually not a good example of a recursive function but what it does is the following:


Assuming we type in k = 3

1. check if c (3) is positive
2. x (1) = x (1) * c (3);
3. call recurse(2);

4. check if c (2) is positive
5. x (3) = x (3) * c (2);
6. call recurse(1);

7. check if c (1) is positive //we could already stop here hence always check if x > 1 (because * 1 doesn't change anything)
8. x (6) = x (6) * c ( 1); //well but this is what it does
9. call recurse (0);

10. check if c(0) positive (it's not ^.^)
11. return x (6);

//it jump back to where we called "recurse (0)" and does the return x; there
12. return x(6);

//it jumps back to where we called "recurse (1)"
13. return x(6);

//it jumps back to where we called "recurse (2)"
14. return x(6);

//jumps finally back to main and prints 6


Defining x as global completly kills the purpose of a recursive function.

This is the "right" way
1
2
3
4
5
6
int recurse(int c) {
if(c == 1)
    return c;
   
return c * recurse(c-1);
}
Last edited on
Thank you very much!
Topic archived. No new replies allowed.