If we use 5 like like in the example, once we got to the else statement wouldn't
return n * factorial(n - 1);
translate to 'return 5 multiplied by the factorial function(5-1); 5 times...
No, it would translate to 'return n multiplied by the factorial function (n-1)' (5 times, because n starts at 5, decrements and enters the else clause until it reaches 0).
- When you first enter the function, n is equal to 5.
- The if clause checks if n is equal to 0. It isn't, so it goes to:
- The else clause. Which translates to 'return 5 multiplied by the factorial function (which you're in) (5 - 1).
- When you enter the factorial function, n is now 4.
Repeat all of those steps until n is equal to 0. The if clause will then be true and the function will return 1.
So 1 is returned from factorial(0). Factorial(1) returns 1 * factorial(0), so 1 * 1 = 1.
Factorial(2) returns 2 * factorial(1), so 2 * 1 = 2.
Factorial(3) returns 3 * factorial(2), so 3 * 2 = 6.
Factorial(4) returns 4 * factorial(3), so 4 * 6 = 24.
Factorial(5) returns 5 * factorial(4), so 5 * 24 = 120.