Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursively sum the integers in an array

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
like image 743
Maggie S. Avatar asked Nov 27 '13 21:11

Maggie S.


1 Answers

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);
like image 95
Óscar López Avatar answered Oct 23 '22 13:10

Óscar López