Complete the code to calculate factorial using recursion.
int factorial(int n) {
if (n == 0) {
return 1;
} else {
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.
int factorial(int n) {
int result = 1;
for (int i = 1; i <= [1]; i++) {
result *= i;
}
return result;
}The loop should run from 1 to n inclusive, so the condition is i <= n.
Fix the error in the recursive Fibonacci function to avoid infinite recursion.
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci([1]) + fibonacci(n - 2);
}
}The recursive calls must reduce the problem size. Using n - 1 and n - 2 correctly moves towards the base case.
Fill both blanks to complete the iterative Fibonacci function.
int fibonacci(int n) {
if (n <= 1) return n;
int a = 0, b = 1, c;
for (int i = 2; i <= [1]; i++) {
c = a + b;
a = [2];
b = c;
}
return b;
}The loop runs until i <= n, and a should be updated to the old b value.
Fill all three blanks to create a recursive function that sums elements of an array.
int sumArray(int[] arr, int index) {
if (index == [1]) {
return 0;
}
return arr[[2]] + sumArray(arr, [3]);
}The base case is when index reaches the array length. We add the current element at index and recurse with index + 1.
