Java Program to Find Sum of Array Elements

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)

  • Create a Scanner object.
  • Read the size of the array .
  • Create an integer array according to the entered size.
  • Initialize sum with 0.
  • Use a for loop to read and store array elements.
  • Use another for loop to add each array element to sum.
  • Print the final sum.
  • Close the Scanner object.
				
					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