Google News
logo
Java program to Sum the Elements of an Array
In the following example of Java program to sum the elements of an array :
Program :
public class SumArrayElements {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        int n = arr.length;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += arr[i];
        }
        System.out.println("The sum of the array is: " + sum);
    }
}
Output :
The sum of the array is: 28
In this program, we first declare an integer array arr and initialize it with the example values {1, 2, 3, 4, 5, 6, 7}. We get the length of the array n and declare an integer variable sum to store the sum of all the elements in the array.

We use a for loop to iterate through the array and add each element to the sum variable. Finally, we print the sum of the array to the console using System.out.println().