Write a program in to find the sum of all elements of the array


This Java program prompts the user to input the size of an array, takes input values from the user, calculates the sum of the values in the array, and then prints out the sum. Here's a brief explanation of what the program does:

  • The program first creates a new Scanner object to read user input from the console.
  • The user is prompted to enter the size of the array.
  • An array of integers 'a' is created with size equal to the value entered by the user.
  • A for loop is used to iterate over each element of the array, prompting the user to enter the value of each element.
  • Another for loop is used to calculate the sum of all elements in the array.
  • The sum of the array is printed to the console.

Source Code

import java.util.Scanner;
class Sum_Array
{
	public static void main(String[] args)
	{   
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l]; 
		int sum = 0; 
		for(int i=0;i<l;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		} 
		for(int e:a)
		{
			sum = sum + e;
		}
		System.out.println("Sum of Array Elements : "+sum);
    }
}
 

Output

Enter the Array Limit :6
Element of a[0] :10
Element of a[1] :20
Element of a[2] :30
Element of a[3] :40
Element of a[4] :50
Element of a[5] :60
Sum of Array Elements : 210

Example Programs