Complete the code to calculate factorial using recursion.
int Factorial(int n) {
if (n == 0) return 1;
return n * Factorial(n [1] 1);
}The factorial of n is n multiplied by factorial of (n-1). So we subtract 1.
Complete the code to iterate through an array and sum its elements.
int SumArray(int[] arr) {
int sum = 0;
for (int i = 0; i [1] arr.Length; i++) {
sum += arr[i];
}
return sum;
}The loop should run while i is less than the array length to avoid out-of-bounds error.
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 [1] 2);
}To get previous Fibonacci numbers, subtract 1 and 2 from n in recursive calls.
Fill both blanks to create a recursive function that sums numbers from 1 to n.
int SumToN(int n) {
if (n == 0) return 0;
return n [1] SumToN(n [2] 1);
}The function adds n to the sum of numbers up to n-1, so use + and - operators.
Fill all three blanks to create a dictionary comprehension that maps numbers to their factorials for 1 to 5.
var factorials = new Dictionary<int, int>() {
{ [1], [2] }
};
int Factorial(int n) {
if (n == 0) return 1;
return n * Factorial(n [3] 1);
}The dictionary starts with key 1 and value Factorial(1). The factorial function subtracts 1 recursively.
