Learnitweb

Java program to print the sum of all elements of an array

This is a programming question for beginners. The logic for this program is simple.

  • Initialize array.
  • Initialize sum to zero (0).
  • Iterate array and get element one by one and add element to the sum.
  • Print sum.
public class SumOfArrayElementsExample {

	public static void main(String[] args) {
		// array to calculate sum
		int [] array = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 99};
		
		//initialize sum to 0
		int sum = 0;
		
		//loop through elements of array and calculate sum
		for(int i=0; i < array.length; i++) {
			sum = sum + array[i];
		}
		
		System.out.println("sum of array elements is: " + sum);
	}

}

Output

Sum of array elements is:160