Complete the code to implement a recursive factorial function.
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n [1] 1);
}The factorial function calls itself with n - 1 to reduce the problem size step by step.
Complete the code to implement an iterative factorial function.
int factorial(int n) {
int result = 1;
for (int i = 1; i [1] n; ++i) {
result *= i;
}
return result;
}The loop runs from 1 up to and including n, multiplying result by each i.
Fix the error in the recursive Fibonacci function to avoid infinite recursion.
int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n [1] 1) + fibonacci(n - 2);
}The recursive call must reduce n by 1 to approach the base case and avoid infinite recursion.
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] n; ++i) {
c = a + b;
a = [2];
b = c;
}
return b;
}The loop runs while i is less than or equal to n. Variable 'a' is updated to the old 'b' value.
Fill all three blanks to create a recursive function that sums numbers from n down to 1.
int sumToOne(int n) {
if (n == 1) return 1;
return n [1] sumToOne(n [2] 1) [3] 0;
}The function adds n to the sum of numbers from n-1 down to 1, with + and - operators.
