Question: Consider the following method that recursively calculates the sum of the elements in an array:
public static int arraySum(int[] arr, int index) {
if (index == arr.length - 1) {
return arr[index];
} else {
return arr[index] + arraySum(arr, index + 1);
}
}
Assume that the arr
parameter is always a non-null array of integers.
a) Write the base case(s) for this recursive method.
b) Explain why it is necessary to have base cases in recursive methods.
c) Provide an example input and step-by-step execution trace of the arraySum
method.
Answer:
a) The base case(s) for this recursive method are:
index
parameter is equal to the last valid index of the array (arr.length - 1
). In this case, the method returns the value of the last element in the array.arr.length == 0
). In this case, the method should return 0, as there are no elements to sum.b) Base cases are necessary in recursive methods to provide a stopping condition for the recursion. Without base cases, the recursion would continue indefinitely, leading to a stack overflow error in most cases. By defining base cases, we ensure that the recursive calls eventually end, providing a correct result.
c) Let's consider the example input arr = [2, 5, 9, 3]
:
arraySum
method is initially called with arr
and index
set to 0.index
is equal to arr.length - 1
, which is false.arr[0]
(2) plus the result of the recursive call of arraySum(arr, index + 1)
.index
set to 1.index
is equal to arr.length - 1
, which is false.arr[1]
(5) plus the result of the recursive call of arraySum(arr, index + 1)
.index
set to 2.index
is equal to arr.length - 1
, which is false.arr[2]
(9) plus the result of the recursive call of arraySum(arr, index + 1)
.index
set to 3.index
is equal to arr.length - 1
, which is true.arr[3]
(3), which is the last element in the array.Therefore, for the input arr = [2, 5, 9, 3]
, the arraySum
method returns 19.