In this tutorial we will learn to write a Java program to create an array and calculate the sum of the elements stored in the array.
Our program will first take the input of the array size and then the elements of the array. Then the sum of the elements of the input array will be calculated and printed as output.
For example
Case 1: If the user enters 4 as the array size and the array elements as 1,2,3,4, the output should be 10.
Case 2: If the user enters 5 as the array size and the array elements as 9,8,7,6,5, the output should be 35.
Find the Sum of Array Elements in Java
import java.util.*;
public class ArrayExample {
public static void main(String[] args) {
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Java Program to find sum of array elements");
System.out.print("Enter the size of array: ");
int size = sc.nextInt();
int arr[] = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("Please give value for index " + i + " : ");
arr[i] = sc.nextInt();
}
for (int i = 0; i < size; i++) {
sum = sum + arr[i];
}
System.out.print("Sum of array elements is " + sum);
}
}
Explanation
For the input array [1, 2, 3, 4, 5], value of sum = 1 + 2 + 3 + 4 + 5 = 15.
Output
Java Program to find sum of array elements
Enter the size of array: 5
Please give value for index 0 : 1
Please give value for index 1 : 2
Please give value for index 2 : 3
Please give value for index 3 : 4
Please give value for index 4 : 5
Sum of array elements is 15