Learn how to find sum of array elements in Java using Scanner and a for loop with a simple program. A for loop reads and stores the elements in the array. Another for loop calculates the sum.
Code Explanation (Step-by-Step)
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int number = sc.nextInt();
int[] arSize = new int[number];
int sum = 0;
System.out.println("Enter array elements:");
for (int i = 0; i < number; i++) {
arSize[i] = sc.nextInt();
}
for (int i = 0; i < number; i++) {
sum = sum + arSize[i];
}
System.out.println("Sum of all the elements of an array: " + sum);
sc.close();
}
}
Output :-
size of input array
2
input array elements
13
sum of input array elements
4
Find Sum of Array Elements Using Java 8 Streams
Here we can calculate the sum of all elements in an integer array using Arrays.stream() and the sum() method.
import java.util.Arrays;
public class ArraySumUsingStream {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = Arrays.stream(numbers).sum();
System.out.println("Sum of array elements: " + sum);
}
}
Output :-
Sum of array elements: 150