In this tutorial we will see how to sum up all the elements of an array.
Program 1: No user interaction
/** * @author: BeginnersBook.com * @description: Get sum of array elements */ class SumOfArray{ public static void main(String args[]){ int[] array = {10, 20, 30, 40, 50, 10}; int sum = 0; //Advanced for loop for( int num : array) { sum = sum+num; } System.out.println("Sum of array elements is:"+sum); } }
Output:
Sum of array elements is:160
Program 2: User enters the array’s elements
/** * @author: BeginnersBook.com * @description: User would enter the 10 elements * and the program will store them into an array and * will display the sum of them. */ import java.util.Scanner; class SumDemo{ public static void main(String args[]){ Scanner scanner = new Scanner(System.in); int[] array = new int[10]; int sum = 0; System.out.println("Enter the elements:"); for (int i=0; i<10; i++) { array[i] = scanner.nextInt(); } for( int num : array) { sum = sum+num; } System.out.println("Sum of array elements is:"+sum); } }
Output:
Enter the elements: 1 2 3 4 5 6 7 8 9 10 Sum of array elements is:55
Karen Mmrdl says
what is ” for( int num : array) “?
Kumar Abhisek says
It is For Each Loop or enhanced for loop introduced in java 1.7
For (int num : array )
Here int is data type for num variable where you want to store all arrays data in otherwords you can say the destination where you want to give all component of arrays.
Here array is the name of the array itself. So all arrays components we are giving to num variable.
sam says
its for each loop it take each element from array and assign to num.
roma says
it is a variation of for loop
basically used in collections
but you can use it to iterate through elements…
hope you get it…
Suman says
If there are more than one array in program how for each loop distinguish each of them , doubt is how to use more than one for each loop in one prog having different different array list?
muhammad says
How do I compute total sum of values in a row in a non uniform array
akram says
how to print average of add numbers in given array int arr[] = {12,22,33,1,-2,3,8,11,9} in java?
Tarun Goyal says
public class AverageIntArray {
public static void main(String[] args) {
int arr[] = {12,22,33,1,-2,3,8,11,9};
float average=0;
float sum = 0;
int length = arr.length;
for (int num : arr){
sum = sum + num;
}
average = sum/length;
System.out.println(average);
}
}
Darshana says
how to find sum of first 5 elements of an array{1,2,3,4,5,6,7,8,9,10} in java using for-each?
nihal says
How to write to finding sum of two 1d array with size of both array enter by the user as like …
Enter size of array :2
Enter element of first array
Stored as
X[0]=1
X[1]=2
Enter element of second array
Y[0]=3
Y[1]=6
Print shows as z[0]=x[0]+y[0]
And z[1]=x[1]+Y[1]