Sums an array recursively. - Java Collection Framework

Java examples for Collection Framework:Array Algorithm

Description

Sums an array recursively.

Demo Code


//package com.java2s;

public class Main {
    /**//w w  w. j  a va2 s  .c o m
     * 
     * Sums an array recursively.
     * 
     * Both indexes are inclusive so sumArray(0,0,array) returns the first value
     * of the array
     * 
     * You can assume that fromIndex is always <= toIndex
     * 
     * Examples:
     * For array {1,2,3,4}
     * sumArray(0,3,array) returns 10
     * sumArray(1,3,array) returns 9
     * sumArray(2,2,array) returns 3
     * 
     * @param fromIndex
     * @param toIndex
     * @param array
     * @return sum of elements
     */
    public static int sumArray(int fromIndex, int toIndex, int[] array) {
        return sumArrayHelper(fromIndex, toIndex, 0, array);
    }

    private static int sumArrayHelper(int start, int end, int sum,
            int[] array) {
        if (start > end) {
            return sum;
        } else {
            sum = sum + array[start]
                    + sumArrayHelper(start + 1, end, sum, array);
            return sum;
        }
    }
}

Related Tutorials