Enter the size of array and then enter all the elements of that array. Now we calculate the sum of elements of the array with the help of for loop.
Here is the source code of the Java Program to Accept Array Elements and Calculate Sum. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Array_Sum
public static void main(String args)
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a = new int[n];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
a[i] = s.nextInt();
sum = sum + a[i];
$ javac Array_Sum.java $ java Array_Sum Enter no. of elements you want in array:5 Enter all the elements: 1 2 3 4 5 Sum:15
Sanfoundry Global Education & Learning Series – 1000 Java Programs.