Post

Created by @nathanedwards
 at November 1st 2023, 5:35:10 am.

Exam Question:

Write a Java method sumOfArray that takes an array of integers and returns the sum of all the elements in the array. Assume that the array is non-null and contains at least one element. You may assume that the sum of the elements will not exceed the maximum value that can be stored in an integer.

You need to write the sumOfArray method and provide the base cases.

Your Answer:

public class Main {
    public static int sumOfArray(int[] arr) {
        // Base case 1: If the array contains only one element, return that element
        if (arr.length == 1) {
            return arr[0];
        }
        
        // Base case 2: If the array is empty, return 0
        if (arr.length == 0) {
            return 0;
        }
        
        // Recursive case: Split the array into two halves (left and right)
        // Calculate the sum of each half recursively and add them together
        int mid = arr.length / 2;
        int[] left = new int[mid];
        int[] right = new int[arr.length - mid];
        System.arraycopy(arr, 0, left, 0, mid);
        System.arraycopy(arr, mid, right, 0, arr.length - mid);
        
        return sumOfArray(left) + sumOfArray(right);
    }
    
    public static void main(String[] args) {
        int[] array1 = {1, 2, 3, 4, 5};
        int[] array2 = {10, -5, 7};
        int[] array3 = {0};
        
        System.out.println("Sum of array1: " + sumOfArray(array1));  // Output: 15
        System.out.println("Sum of array2: " + sumOfArray(array2));  // Output: 12
        System.out.println("Sum of array3: " + sumOfArray(array3));  // Output: 0
    }
}

Explanation:

The sumOfArray method takes an array of integers as input and returns the sum of all the elements in the array.

  • Base Case 1: If the array contains only one element (length equals 1), we simply return that element.
  • Base Case 2: If the array is empty (length equals 0), we return 0, as there are no elements to sum.
  • Recursive Case: If the array has more than one element, we split it into two halves, recursively calculate the sum of each half, and then add them together.

In the main method, we test the sumOfArray method with three different arrays: array1 = {1, 2, 3, 4, 5}, array2 = {10, -5, 7}, and array3 = {0}. We print the sum of each array using System.out.println(). The expected outputs are shown as comments next to each println statement.