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
The issue is that
a[n-1]
is anint
, whereassumOfArray
expects an array ofint
.Hint: you can simplify things by making
sumOfArray
take the array and the starting (or ending) index.a
is anint
array. Thusa[n-1]
is anint
. You are passing anint
tosumOfArray
which expects an array and not anint
.Try this if you don't want to pass the length of the array :
Offcourse you need to check if the array is empty or not.
This is the one recursive solution with complexity O(N).and with input parameter A[] only.
You can handle null and empty(0 length) case specifically as Its returning 0 in this solution. You throw Exception as well in this case.
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.