recursively sum the integers in an array

前端 未结 9 1005
不思量自难忘°
不思量自难忘° 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:56

    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.

提交回复
热议问题