Back to questionsWhich line, added at the top of
JuniorDebuggingCommon
Which line, added at the top of factorial, makes factorial(3) return 6?
int factorial(int n) {
return n * factorial(n - 1);
}if (n == 0) { return 1; }
- Expecting
return 0;to work:factorial(3)would then compute 3 · 2 · 1 · 0 = 0, so the base case of a product returns1. - Expecting the calls to end by themselves: with no base case every call makes one more call, so no call ever returns.
- What does the fixed
factorialdo when it is called with a negativen? - How would you write
factorialwith a loop instead of recursion?
Fix
The base case stops the recursion: at n == 0 the function returns 1 and makes no further call. The value 1 leaves a product unchanged, so factorial(3) computes 3 · 2 · 1 · 1 and returns 6.
int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}