When does factorial stop calling itself?
How factorial chooses a path
Theo Brooks
If this call’s n is zero, return 1, and otherwise call factorial again.
Transcript
When you call factorial with 2, that number becomes this call’s n. It decides which of 2 paths the call takes.
Your last line asks for the factorial of 2, so n is 2, and that’s the number this call checks. In the zero test, the double equals sign asks whether n has the same value as 0. The double equals sign gives true only when those values match. Here it compares 2 with 0, so the result is false because those numbers don’t match.
Notice how return 1 sits farther to the right than the if line, so it belongs only to the true path. So the marker skips return 1 and follows the false path to the product line, which returns n times the factorial of n minus 1. That’s the recursive case because factorial calls itself to find its answer. In this recursive case, the product has to wait for that other call’s answer.
Look at the input that product needs next: 2 minus 1 is 1. So the current call asks for the factorial of 1, and its n is 1. The marker goes back to the zero test, which now compares 1 with 0 and gives false again. Since there’s no match, the marker skips return 1 and follows the false path to the product line for another recursive case.
Now look at the input this product needs: 1 minus 1 is 0. So the current call asks for the factorial of 0, with 0 as its n. The marker goes back to the same zero test, and this time 0 equals 0, so the result is true. Now the marker follows the true path to return 1, so this call ends with the answer 1. This is the base case because it gives an answer before the call reaches the product line that would call factorial again. Here the base case gives back 1 even though its input was 0. So each call tests its own n: if it’s 0, the call answers right away, and if it isn’t, factorial calls itself again.