Java Program to Find Sum of Elements of an Array

  • How to add all elements of an array using loop in Java.
  • Write a Java program to calculate sum of all array elements.

Given an array of N integers. We have to find the sum of all elements of array from index 0 to N-1.

Input Array
3 7 2 9 4 10 11 0 -1
Sum of Array Elements
45
Algorithm to find sum of all array elements
Let inputArray is an integer array having N elements.
  • Declare an integer variable 'sum' and initialize it to 0. We will use 'sum' variable to store sum of elements of array.
  • Using for-each loop, we will traverse inputArray and add each element to sum variable.
  • After termination of for-each loop, "sum" variable will contain the sum of all array elements.

Java program to add all elements of an array

package com.tcc.java.programs;

import java.util.*;

public class ArrayElementSum {
    public static void main(String args[]) {
        int count, sum = 0, i;
        int[] inputArray = new int[500];
        Scanner in = new Scanner(System.in);

        System.out.println("Enter number of elements");
        count = in .nextInt();
        System.out.println("Enter " + count + "elements");
        for (i = 0; i < count; i++) {
            inputArray[i] = in .nextInt();
        }

        for (int num: inputArray) {
            sum = sum + num;
        }

        System.out.println("Sum of all elements = " + sum);
    }
}
Output
Enter number of elements
5
Enter 5elements
3 8 1 7 2
Sum of all elements = 21