recursively sum the integers in an array

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

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

提交回复
热议问题