// Program to calculate the sum of all elements in an array // both iteratively and recursively. // Demonstrates public-private pair approach to recursion. public class ArraySum { public static void main(String[] args) { int[] numbers = {5, 1, 0, -4, 12, 2, -7, 2}; System.out.println(arraySumIter(numbers)); System.out.println(arraySumRecur(numbers)); } // calculates the sum of the elements in arr public static int arraySumIter(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // calculates the sum of the elements in arr // // public version of the method that has the signature // expected by the client public static int arraySumRecur(int[] arr) { return arraySumRecur(arr, 0); } // calculates the sum of the elements in arr // // private version that includes an additional parameter // to track where in the array we are currently working private static int arraySumRecur(int[] arr, int index) { if (arr.length == index) { return 0; } else { // get current element int elem = arr[index]; // sum up rest of array int sum = arraySumRecur(arr, index + 1); // return current element plus sum of rest return elem + sum; } } }