Exam question:
Consider the following code snippet that calculates the sum of all numbers from 1 to n, where n is a positive integer:
public static int sumOfNumbers(int n) {
if (n <= 0) {
return 0;
}
return n + sumOfNumbers(n - 1);
}
Assume that the base case for the sumOfNumbers() method is when n is less than or equal to 0, in which case it returns 0.
Write at least two base cases that test the behavior of the sumOfNumbers() method for different values of n.
Explain the purpose of base cases and why they are essential in recursive functions.
Answer:
Base cases in recursive functions serve as the terminating condition that stops the recursion and provides a result. They are essential to avoid infinite recursion and to handle special or edge cases that cannot be solved through recursive calls.
Test Case 1: n = 0
Let's consider the base case where n is equal to 0. In this case, the sumOfNumbers() method should return 0.
int result = sumOfNumbers(0);
The recursive calls will be as follows:
sumOfNumbers(0)
return 0 (base case)
The return value of 0 matches the expected result, as the sum of numbers from 1 to 0 is 0.
Test Case 2: n = 5
Now, let's consider a base case where n is a positive integer, such as 5. In this case, the sumOfNumbers() method should return the sum of numbers from 1 to 5, which is 15.
int result = sumOfNumbers(5);
The recursive calls will be as follows:
sumOfNumbers(5)
return 5 + sumOfNumbers(4)
return 4 + sumOfNumbers(3)
return 3 + sumOfNumbers(2)
return 2 + sumOfNumbers(1)
return 1 + sumOfNumbers(0)
return 0 (base case)
By substituting the return values backward, we get:
sumOfNumbers(5)
return 5 + sumOfNumbers(4)
return 4 + sumOfNumbers(3)
return 3 + sumOfNumbers(2)
return 2 + sumOfNumbers(1)
return 1 + sumOfNumbers(0)
return 1 + 0 (base case)
return 1
The return value of 1 matches the expected result, as the sum of numbers from 1 to 5 is indeed 15.
In conclusion, the base cases in the sumOfNumbers() method ensure that the recursion terminates when n reaches a specific condition. With proper base cases, the recursive function can handle different scenarios and provide accurate results. In the test cases above, the base cases help return the appropriate results for both edge cases (n = 0) and positive integer inputs (n = 5).