Write a program to calculate the average value of array elements


This Java program prompts the user to input the limit of an array, then takes input values from the user and calculates the sum and average of the array values. 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 limit of the array.
  • An array of integers 'a' is created with the size equal to the limit 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 average of the array is calculated by dividing the sum by the length of the array.
  • Finally, the sum and average are printed to the console.

Source Code

import java.util.Scanner;
class Average
{
	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 i=0; i < l ; i++)
			sum = sum + a[i];
 
		double ave = sum / l;
		System.out.println("Sum of Array Value : " + sum); 
		System.out.println("Average of Array Value : " + ave); 
    }
}
 

Output

Enter the Array Limit :5
Element of a[0] :1
Element of a[1] :20
Element of a[2] :30
Element of a[3] :45
Element of a[4] :67
Sum of Array Value : 163
Average of Array Value : 32.0

Example Programs