Sum of elements in an Array in Java

Today we will see how to find the sum of elements in an array in Java.

It is a simple java program in which we will iterate through each element in the array, and keep on adding it to a sum variable until we reach the final element.

So let’s go straight to the code:

import java.util.*;
public class test
{
  public static void main(String[] args)
  {
       int sum=0;
       Scanner sc=new Scanner(System.in);
       int arr[]=new int[10];
       System.out.println("Enter elements in the array");
       for(int i=0;i<=9;i++)
       {
    	   arr[i]=sc.nextInt();
    	   sum=sum+arr[i];
       }
       System.out.println("Sum of elements of the array is  "+sum);
       
       
  }
}

If there is a two dimension array instead of a single dimension array the logic remains the same, we just need to iterate to each element of the two-dimensional array and add each element to the sum.




In our program, we have used a for a loop. inside our loop, we take each element and adding it. You can notice that we take a variable “sum” and assign 0 to it. We are just adding one by one element to this variable and finally, it stores the sum of all elements from the array.

The above code will generate the following result on the compilation that you can see below:

Enter elements in the array
40
24
46
42
12
19
30
33
36
47
Sum of elements of the array is  329
Enter elements in the array
12
12
13
43
23
9
16
36
52
22
Sum of elements of the array is 238

Hope this helped you out to find the sum of elements of an array in Java programming.

Have a nice day ahead and learn even more.

Also Read:

Python program to create a class which performs basic calculator operations

How to find the difference or gap of days between two dates in python

Find the next greater number from the same set of digits in C++


Leave a Reply

Your email address will not be published. Required fields are marked *