Find the sum of elements in an array

Write a Java program to find the sum of elements in an array.

The provided Java program calculates the sum of the elements in an array.

class Main {
    public static void main(String[] args) {
        int[] arr = {6, 6, 7, 8, 8, 9};
        int sum = sumOfArr(arr);
        System.out.println("Sum of elements in the array: " + sum);
    }

    public static int sumOfArr(int[] arr) {
        int sum = 0;
        for (int num : arr) {
            sum += num;
        }
        return sum;
    }
}

Output:

Sum of elements in the array: 44

How It Works

  1. Input Array:
    • The input array is {6, 6, 7, 8, 8, 9}.
  2. sumOfArr Method:
    • The sumOfArr method loops through each element of the array using an enhanced for loop.
    • It adds each number in the array to the sum variable.
  3. Returning the Sum:
    • After looping through all the elements, the total sum is returned to the main method.
  4. Output:
    • The sum of the array elements is printed.

Execution:

  1. Initialize sum = 0.
  2. Loop through the array:
    • Add 6 to sum → sum = 6
    • Add 6 to sum → sum = 12
    • Add 7 to sum → sum = 19
    • Add 8 to sum → sum = 27
    • Add 8 to sum → sum = 35
    • Add 9 to sum → sum = 44
  3. Return sum = 44.

Advantages

  1. Simple and Efficient:
    • The code uses a basic loop to iterate over the array and calculate the sum, which is efficient for arrays of reasonable size.
  2. Readability:
    • The method is clear and easy to understand, making it straightforward for other developers to follow.

Edge Cases

  1. Empty Array:
    • Input: arr = {}
    • Output: Sum of elements in the array: 0
  2. Array with Negative Numbers:
    • Input: arr = {-1, 5, -3, 2}
    • Output: Sum of elements in the array: 3
  3. All Zeroes:
    • Input: arr = {0, 0, 0, 0}
    • Output: Sum of elements in the array: 0

Leave a Reply