7

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
1
  • 1
    Using recursion is not only more complicated but much slower in this case. I assume this is just an exercise. Commented Nov 27, 2013 at 22:09

10 Answers 10

19

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);
1
  • 5
    It's not good form to just provide answers to a student in a class. They don't learn. You need to explain what's wrong. Commented May 16, 2015 at 17:19
6

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.

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

4
  • I believe you could also use Arrays#CopyOfRange too. Commented Nov 27, 2013 at 21:48
  • 1
    Seriously? The fact that this will (horribly) work doesn't mean it is the right approach. Commented Nov 27, 2013 at 21:50
  • @LuiggiMendoza Arrays.copyOf(a, a.length-1); does what the op expected a[n-1] to do.
    – Cruncher
    Commented Nov 28, 2013 at 13:39
  • Yes, I know, but why to create a whole copy of the array and wasting memory and linear processing time (which will make this algorithm O(n^2) in both memory and time) when you can just pass an integer value with the next element of the array to use, and keep this algorithm O(n) (in both memory and time)? As I said in my last comment: the fact it works (compiles, run and get the expected result) does not mean it is the right approach. Commented Nov 28, 2013 at 14:49
2

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);
    }
}
1
  • This solution uses more memory, but it helped me understand a core recursion concept, so thanks.
    – mach3
    Commented Feb 22, 2022 at 18:07
1

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.

1

Try this if you don't want to pass the length of the array :

private static int sumOfArray(int[] array) {

        if (1 == array.length) {
            return array[array.length - 1];
        }

        return array[0] + sumOfArray(Arrays.copyOfRange(array, 1, array.length));
    }

Offcourse you need to check if the array is empty or not.

1

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.


/*
 * Complexity is O(N)
 */
public int recursiveSum2(int A[])
{
    if(A == null || A.length==0)
    {
        return 0;
    }
    else
    {
        return recursiveSum2Internal(A,A.length-1);
    }
}
private int recursiveSum2Internal(int A[],int length)
{
    if(length ==0 )
    {
        return A[length];
    }
    else
    {
        return A[length]+recursiveSum2Internal(A, length-1);
    }
}
1

without any predefined function.

public static int sum(int input[]) {

 int n = input.length;

  if (n == 0)  // base case
  return 0;
  
    int small[]=new int[n-1];
    
    for(int i=1;i<n;i++)
    {
        small[i-1]=input[i];
    }

      return input[0]+sum(small);
    
}
1
  • 1
    Please add the method signature within the formatted code.
    – Satheesh
    Commented Jan 10, 2022 at 7:59
0
private static int sum(int[] arr) {
    // TODO Auto-generated method stub
    int n = arr.length;

    if(n==1)
    {
        return arr[n-1];
    }

    int ans = arr[0]+sum(Arrays.copyOf(arr, n-1));

    return ans;
}
0

Simplified version:

//acc -> result accumlator, len - current length of array

public static int sum(int[] arr, int len, int acc) {
    return len == 0 ? acc :  sum(arr, len-1,  arr[len-1]+ acc); 
}   
public static void main(String[] args)  {
    int[] arr= { 5, 1, 6, 2};
    System.out.println(sum(arr, arr.length, 0));
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.