Returns the sum of all the elements in the array - Java Collection Framework

Java examples for Collection Framework:Array Algorithm

Description

Returns the sum of all the elements in the array

Demo Code


//package com.java2s;

public class Main {
    /**//from w w w  . j  a va2  s. c om
     * Returns the sum of all the elements in the array
     * 
     * This is difficult to do recursively without duplicating the array
     * 
     * You can assume the array has at least one element
     * 
     * Examples:
     * For array {1,2,3,4}
     * sumArray(0,3,array) returns 10
     * 
     * @param array
     * @return sum of array
     */
    public static int sumWholeArray(int[] array) {
        return sumWholeArrayHelper(0, 0, array);
    }

    private static int sumWholeArrayHelper(int index, int sum, int[] array) {
        if (index > array.length - 1) {
            return sum;
        } else {
            return sum + array[index]
                    + sumWholeArrayHelper(index + 1, sum, array);
        }
    }
}

Related Tutorials