Java program to sum the elements of an array

Java program to sum the elements of an array


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

Post a Comment

Previous Post Next Post