Java Program to find average of array elements
Program
import java.util.Scanner;
public class AverageOfNumbersUsingArray {
public static void main(String[] args) {
System.out.println("Enter the required size of the array: ");
Scanner reader = new Scanner(System.in);
int size = reader.nextInt();
Integer inputArray[] = new Integer[size];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < size; i++) {
inputArray[i] = reader.nextInt();
}
double sum = 0;
double average = 0;
for(int i =0; i< size; i++){
sum = sum + inputArray[i];
}
average = sum/size;
System.out.println("Average of given numbers is: "+ average);
}
}
This Java program calculates the average of elements in an array.
-
Input Array Size and Elements:
- The user is prompted to input the size of the array (
size). - An integer array
inputArray[]is created with the specified size. - The user enters the elements of the array, which are stored in
inputArray. - The program dynamically handles arrays of any size and calculates the average based on user input.
- The user is prompted to input the size of the array (
-
Sum Calculation:
- A variable
sumis initialized to0. - A
forloop iterates through the array to calculate the total sum of the elements by adding each element tosum.
- A variable
-
Average Calculation:
- The average is calculated by dividing the total sum (
sum) by the number of elements in the array (size). - The result is stored in the
averagevariable. - The
sumandaveragevariables are declared asdoubleto ensure precision when performing division.
- The average is calculated by dividing the total sum (
-
Output:
- The calculated average is printed to the console.
Output
javac .\AverageOfNumbersUsingArray.java
java AverageOfNumbersUsingArray
Enter the required size of the array:
4
Enter the elements of the array:
11
22
33
44
Average of given numbers is: 27.5