How to find the sum of all elements in an integer array in Java

Share

In this shot, we discuss how to find the sum of elements in an integer array in Java.

The sum of the elements of an integer array can be calculated by adding all the elements present in an integer array together.

Solution approach

We will approach this problem by receiving the user input of a particular element of an array. Then, we will add the element to a temporary variable, that is continuously initialized with 0, by using the loop from the starting index to the last index of the array.

Code

Let’s take a look at the code.

The user needs to pass 2 inputs in order to run the code :

  • The total number of elements (N).
  • The (N) elements of the array.

Input format:

5 1 2 3 4 7

Where 5 is the number of elements in the array and 1 2 3 4 7 are those 5 elements.

import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
int sum=0;
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
sum=sum+a[i];
}
System.out.print("Sum of integers in the array is: "+sum);
}
}

Enter the input below

Explanation

  • In line 1, we import the required package.

  • In line 2, we initiate a class Main.

  • In line 6, we make an object as Scanner class to use the methods available in it.

  • In line 7, we print the input of the size of the integer array and store it in a variable of int data type.

  • In line 8, we declare an integer array of size input.

  • In line 9, we initialize a variable of int data type with 0, which stores the sum of the elements traversed at a particular instant.

  • In lines 10 to 14, we use a for loop to get the input of elements for every index of the array, add the element to the variable, and store the sum till the loop ends.

  • In line 15, we display the output as the sum of elements along with a message.