recursively sum the integers in an array

前端 未结 9 1014
不思量自难忘°
不思量自难忘° 2020-12-06 03:01

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         


        
9条回答
  •  日久生厌
    2020-12-06 03:45

    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);
    

提交回复
热议问题