Write a program to print sum values of an array


This Java program takes 10 integers as input from the user, stores them in an array a, and then calculates the sum of all the values in the array using a for-each loop.

Here is a breakdown of the code:

  • Declare an integer array a of size 10.
  • Declare an integer variable sum and initialize it to 0.
  • Use a for loop to iterate from 0 to 9.
  • Inside the loop, create a Scanner object to read input from the user.
  • Prompt the user to enter the value for the current index of the array.
  • Read the integer input from the user and store it in the current index of the array.
  • After the loop, use a for-each loop to iterate over the elements in the array a.
  • For each element i in the array, add its value to the sum variable.
  • Print the sum of all the values in the array.

Source Code

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

Output

Element of a[0] :1
Element of a[1] :2
Element of a[2] :3
Element of a[3] :4
Element of a[4] :5
Element of a[5] :6
Element of a[6] :7
Element of a[7] :8
Element of a[8] :9
Element of a[9] :10
Sum Values of Array : 55

Example Programs