recursively sum the integers in an array
The solution is simpler than it looks, try this (assuming an array with non-zero length):
public int sumOfArray(int[] a, int n) {
if (n == 0)
return a[n];
else
return a[n] + sumOfArray(a, n-1);
}
Call it like this:
int[] a = { 1, 2, 3, 4, 5 };
int sum = sumOfArray(a, a.length-1);
The issue is that a[n-1]
is an int
, whereas sumOfArray
expects an array of int
.
Hint: you can simplify things by making sumOfArray
take the array and the starting (or ending) index.
a[n-1]
is getting the int at n-1, not the array from 0 to n-1.
try using
Arrays.copyOf(a, a.length-1);
instead