集册 Java实例教程 返回数组中所有元素的和

返回数组中所有元素的和

欢马劈雪     最近更新时间:2020-01-02 10:19:05

413
返回数组中所有元素的总和


//package com.nowjava;
/** 
 来自 时代Java**/


public class Main {

    /**

     * 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 {

展开阅读全文