/**** * * This class illustrates how to compute the sum of an array recursively. The * public sum method takes an array of integers and returns the sum of all its * elements. A private "helper" method takes an array and an integer postion * in the array. * * The reason for the helper method is to avoid inefficient array copying to * create a sub-array. Rather than creating a sub-array by copying, the helper * method takes a full array plus an integer position that indicates the * beginning of the sub-array. * */ public class RecursiveSum { /** * Return the sum of the given array. Return 0 for an empty array. Assume * the array is not null. */ public int sum(int a[]) { return sum(a, 0); } /** * Return the sum of the given array, starting at the given position. If * the position is equal to the length of the array, return 0. */ private int sum(int a[], int position) { /** * Base Case: Return a sum of 0 if position is at the end of the array. */ if (position == a.length) return 0; /** * Recursive Step: Return the sum of the first element of the array * with the recursive sum of the rest of the array. The first element * is at a[position]. The rest of the array is represented by the full * array with the position incremented by 1. */ return a[position] + sum(a, position + 1); } }