recursively sum the integers in an array
Solution 1
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);
Solution 2
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.
Solution 3
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
Solution 4
How about this recursive solution? You make a smaller sub-array which contains elements from the second to the end. This recursion continues until the array size becomes 1.
import java.util.Arrays;
public class Sum {
public static void main(String[] args){
int[] arr = {1,2,3,4,5};
System.out.println(sum(arr)); // 15
}
public static int sum(int[] array){
if(array.length == 1){
return array[0];
}
int[] subArr = Arrays.copyOfRange(array, 1, array.length);
return array[0] + sum(subArr);
}
}
Solution 5
a
is an int
array. Thus a[n-1]
is an int
. You are passing an int
to sumOfArray
which expects an array and not an int
.
Maggie S.
No longer a student and working my first job! I'm in a great place, but I am always learning and will never stop asking questions. Love this community.
Updated on January 10, 2022Comments
-
Maggie S. over 2 years
I have a program that I'm trying to make for class that returns the sum of all the integers in an array using recursion. Here is my program thus far:
public class SumOfArray { private int[] a; private int n; private int result; public int sumOfArray(int[] a) { this.a = a; n = a.length; if (n == 0) // base case result = 0; else result = a[n] + sumOfArray(a[n-1]); return result; } // End SumOfArray method } // End SumOfArray Class
But I'm getting three error which are all related, I believe, but I can't figure out why it is finding a type of null:
SumOfArray.java:25: sumOfArray(int[]) in SumOfArray cannot be applied to (int) result = a[n] + sumOfArray(a[n-1]); ^ SumOfArray.java:25: operator + cannot be applied to int,sumOfArray result = a[n] + sumOfArray(a[n-1]); ^ SumOfArray.java:25: incompatible types found : <nulltype> required: int result = a[n] + sumOfArray(a[n-1]); ^ 3 errors