Complete the code to return 1 when n is 0, the base case of recursion.
function factorial(n: number): number {
if (n === [1]) {
return 1;
}
return n * factorial(n - 1);
}The base case for factorial is when n is 0, returning 1 stops recursion.
Complete the code to call factorial recursively with n-1.
function factorial(n: number): number {
if (n === 0) {
return 1;
}
return n * factorial([1]);
}The recursive call reduces n by 1 each time to reach the base case.
Fix the error in the base case condition to stop infinite recursion.
function sumToN(n: number): number {
if (n [1] 0) {
return 0;
}
return n + sumToN(n - 1);
}The base case should check if n equals 0 to stop recursion.
Fill both blanks to create a recursive function that counts down to zero.
function countdown(n: number): void {
if (n [1] 0) {
console.log('Done');
return;
}
console.log(n);
countdown(n [2] 1);
}The base case checks if n is exactly 0, and the recursive call subtracts 1.
Fill all three blanks to create a recursive function that sums numbers from 1 to n.
function sumNumbers(n: number): number {
if (n [1] 1) {
return 1;
}
return n [2] sumNumbers(n [3] 1);
}The base case checks if n equals 1, then returns 1. The recursive call adds n to sumNumbers(n - 1).
