How to sum the elements of an array in Java Program?

  Java Interview Q&A

Dear readers, today we will create a Java Program to sum up all the elements of an array. his can be solved by looping through the array and add the value of the element in each iteration to variable sum.

Sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.

1. Java Program to sum the elements of an array

public class SumOfArray {
    public static void main(String[] args) {
        //Initialize array
        int [] arr = new int [] {1, 2, 3, 4, 5};
        int sum = 0;
        //Loop through the array to calculate sum of elements
        for (int i = 0; i < arr.length; i++) {
           sum = sum + arr[i];
        }
        System.out.println("Sum of all the elements of an array: " + sum);
    }
}

Output:

Sum of all the elements of an array: 15

2. Java Program to sum the elements of an array

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

Output:

Sum of array elements is:160

Read Here Complete Java Tutorial – Click Here

LEAVE A COMMENT