In this programming tutorial, we will learn to write a java program to calculate the sum of all the elements in an array by taking array input from the user.
The for loop in the program runs starting from 0 (array index starts from 0) to the total length of an array (i.e. till the last index).
Although it is quite simple, you still need to have an idea of the proper function of following in java:
Java Program to Find the Sum of all the Elements in an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //sum of an array(user inputs) in java import java.util.Scanner; public class SumofElements { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int[] array = new int[10]; int sum = 0; System.out.println("Enter the elements in an array:"); for (int i=0; i < 10; i++) { array[i] = sc.nextInt(); } //Sum calculation for( int num : array) { sum = sum + num; } System.out.println("Sum of the elements is :"+sum); } } |
Output:
Enter the elements in an array:
3
4
2
6
8
12
4
5
7
9
0
Sum of the elements is :60