Participation Recursion 13.4.3: Compute recursively to determine the sum of values in an array
Assume you have the following method:
public static int sum(int[] a) {
// To compute the sum of the values in an array, add the first value to the sum of the remaining values, computing recursively
// Rearrange the following lines to design a recursive helper method to solve this problem
// Not all lines are useful
if (a.length == 0) {
return 0;
}
if (a.length == 1) {
return a[0];
}
return a[0] + sumHelper(a, 1);
}
public static int sumHelper(int[] a, int start) {
if (start == a.length) {
return a[start];
}
return a[start] + sumHelper(a, start + 1);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int[] myArray = new int[size];
for (int i = 0; i < size; i++) {
myArray[i] = in.nextInt();
}
int sum = sum(myArray);
System.out.println("Sum: " + sum);
}