// Hunter Schafer, CSE 143 // Program prints out the sum of an array import java.util.Arrays; public class RecursionExamples { public static void main(String[] args) { int[] arr = {3, 1, 7, 2}; System.out.println("The sum of " + Arrays.toString(arr) + " is " + sum(arr)); } // pre: arr is not null // returns the sum of all the elements in the given arr public static int sum(int[] arr) { return sum(arr, 0); } // pre: arr is not null, 0 <= index <= arr.length // returns the sum of the elements of arr starting at // the given index to the end. private static int sum(int[] arr, int index) { if (index == arr.length) { return 0; } else { // arr[0] + arr[1] + arr[2] + ... // sum one number with the rest of the numbers // arr[0] + sum(of arr starting at 1) // arr[1] + sum(of arr starting at 2) // arr[2] + sum(of arr starting at 3) return arr[index] + sum(arr, index + 1); } } /* * int sum = 0; * for (int i= 0; i < arr.lenght; i++) { * sum += arr[i]; * } * return sum; * * */ }