Last Updated:

How do I find the sum of the elements in an array? Program in Java

 

Sum of elements of an already initialized array in Java

package com.p-qc;


public class SumOfArray{
public static void main(String args[]){
int[] array = {10, 30, 20, 50, 40, 10};
int sum = 0;
// loop to iterate over each element of the array
for( int num : array) {
// summation of each element of the array
sum = sum + num;
}
System.out.println("The sum of the array elements is: " + sum);
}
}

The result of this program:

 

Sum of elements of user-entered array in Java

 

The result of the second program for summing the elements of the array in Java: