## Java Program to Print Sum of given Array Elements

In previous  post we learnt how to check given element is present in array or not. In this post we will learn how to print sum of given array elements. So let's get started... :)

### Step by step logic of the given program:

1. Accept array limit from user store it in variable say lim.

2. Accept elements from user. Run a for loop from 0 to arr.length-1 and store elements one by one in array:

``````for(int i =0;i<arr.length;i++) {
arr[i]=sc.nextInt();
}``````

3. After that store sum of  all elements in variable called sum using for-each loop (you can also use simple for loop).

``````for(int ele:arr) {
sum+=ele;
}``````

4. Last print sum of array elements stored in sum variable.

## Java Program to Print Sum of Given Array Elements :

``````
import java.util.Scanner;

public class ArraySumExample {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int sum=0;

System.out.println("How many elements you want to enter: ");
int lim = sc.nextInt();
int[] arr= new int[lim];
//Accept Elements
System.out.println("Enter "+lim+" elements: ");
for(int i =0;i<arr.length;i++) {
arr[i]=sc.nextInt();
}
//for-each loop
for(int ele:arr) {
sum+=ele;
}
System.out.println("Sum of given array elements is: "+sum);

}

}

``````

Output of the above program is

How many elements you want to enter:
5
Enter 5 elements:
5
7
8
10
20
Sum of given array elements is: 50