Complete the code to calculate factorial using recursion.
function factorial(n: number): number {
if (n === 0) {
return 1;
}
return n * factorial([1]);
}The recursive call must reduce the problem size by 1 each time, so n - 1 is correct.
Complete the code to calculate factorial using iteration.
function factorialIter(n: number): number {
let result = 1;
for (let i = 1; i <= [1]; i++) {
result *= i;
}
return result;
}The loop runs from 1 up to n, so the condition should be i <= n.
Fix the error in the recursive Fibonacci function to avoid infinite recursion.
function fib(n: number): number {
if (n <= 1) {
return n;
}
return fib([1]) + fib(n - 2);
}The Fibonacci function calls fib(n-1) and fib(n-2) to reduce problem size correctly.
Fill both blanks to create a recursive function that sums numbers from n down to 1.
function sumToN(n: number): number {
if (n === 0) {
return 0;
}
return n [1] sumToN([2]);
}To sum numbers from n down to 1, add n to sumToN(n - 1).
Fill all three blanks to create an iterative function that reverses a string.
function reverseString(str: string): string {
let reversed = '';
for (let i = [1]; i [2] -1; i[3]) {
reversed += str[i];
}
return reversed;
}The loop starts from the last index (length - 1), continues while i > -1, and decrements i each time.
