// Erika Wolfe // Prints out the sum of an array import java.util.*; public class Recursion2 { public static void main(String[] args) { int[] arr = {3, 1, 7, 2}; System.out.println("The sum of " + Arrays.toString(arr) + " is " + sum(arr)); } // post: returns the sum of arr public static int sum(int[] arr) { return sum(arr, 0); } // pre: 0 <= index <= arr.length // post: returns the sum of arr starting at the given index private static int sum(int[] arr, int index) { // what is the easiest index to sum in an array? if (index == arr.length) { return 0; } else { return arr[index] + sum(arr, index + 1); // this index + sum of rest of array } } // // iterative solution for the same problem // public static int sum2(int[] arr) { // // values that we're using: i, sum, arr // int sum = 0; // for (int i = 0; i < arr.length; i++) { // sum += arr[i]; // } // return sum; // } }