Recursive – I cannot understand how it really works

I can’t understand something about the recursive function. Let’s assume that i’m calculating the factorial of an x number. The code would look like this:

#include <iostream>
using namespace std;

int factorial(int y){
    if(y == 0)
        return 1;
    return y * factorial(y-1);


}

int main() {
    int n;
    cin >> n;
    cout << factorial(n);



    return 0;
}

And there, from my understanding, i have an base case, which will stop the function at one point. Good until now, after the base case, the next statement will return the x * factorial(x-1). Lets assume that we want to find the factorial of number “4”. It will look something like that:

x = 5 --> x != 0, return 5 * factorial(4) | 
x = 4 --> x != 0, return 4 * factorial(3) | 
x = 3 --> x != 0, return 3 * factorial(2) |
x = 2 --> x != 0, return 2 * factorial(1) |
x = 1 --> x != 0, return 1 * factorial(0) |

And now, because x equals 0, the next statement will run:

if(x == 0)
  return 1;

What i don’t understand: if the function return 1, the program should return exactly the number “1”, why and how it return what was calculated on the recursive statement.

Answer

1) x = 5 --> x != 0, return 5 * factorial(4) | 
2) x = 4 --> x != 0, return 4 * factorial(3) | 
3) x = 3 --> x != 0, return 3 * factorial(2) |
4) x = 2 --> x != 0, return 2 * factorial(1) |
5) x = 1 --> x != 0, return 1 * factorial(0) |

factorial(0) will return 1; hence line 5) will be as follows:

  1. x = 1 --> x != 0, return 1 * 1 | which is factorial(1)

factorial(1) will return 1; hence line 4) will be as follows:

  1. x = 2 --> x != 0, return 2 * 1 | which is factorial(2)

factorial(2) will return 2; hence line 3) will be as follows:

  1. x = 3 --> x != 0, return 3 * 2 | which is factorial(3)

factorial(3) will return 6; hence line 2) will be as follows:

  1. x = 4 --> x != 0, return 4 * 6 | which is factorial(4)

factorial(4) will return 24; hence line 1) will be as follows:

  1. x = 5 --> x != 0, return 5 * 24 | 120

See figure for visualization