Java Program to Calculate Average of an Array

Write a Java program to calculate average of an array element using for loop. This Java example allows entering array size and items. Next, for loop will iterate each array item and add to arrSum variable. Next, we are diving that sum with array length or size.

package RemainingSimplePrograms;

import java.util.Scanner;

public class AverageofArray1 {
	private static Scanner sc;
	public static void main(String[] args) {
		int Size, i;
		double arrSum = 0, arrAvg = 0;
		
		sc = new Scanner(System.in);		
		System.out.print("Enter the Array size = ");
		Size = sc.nextInt();
		
		double[] arr = new double[Size];
		
		System.out.format("Enter Array %d elements  = ", Size);
		for(i = 0; i < Size; i++) 
		{
			arr[i] = sc.nextDouble();
		}
		
		for(i = 0; i < Size; i++) 
		{
			arrSum = arrSum + arr[i];
		}
		arrAvg = arrSum / arr.length;
		
		System.out.format("\nThe Sum of Array Items     = %.2f", arrSum);
		System.out.format("\nThe Average of Array Items = %.2f", arrAvg);
	}
}
Java Program to Calculate Average of an Array

Java Program to Calculate Average of an Array using a while loop

package RemainingSimplePrograms;

import java.util.Scanner;

public class AverageofArray2 {
	private static Scanner sc;
	public static void main(String[] args) {
		int Size, i = 0;
		double arrSum = 0, arrAvg = 0;
		
		sc = new Scanner(System.in);		
		System.out.print("Enter the Array size = ");
		Size = sc.nextInt();
		
		double[] arr = new double[Size];
		
		System.out.format("Enter Array %d elements  = ", Size);
		while(i < Size) {
			arr[i] = sc.nextDouble();
			arrSum = arrSum + arr[i];
			i++;
		}
		
		arrAvg = arrSum / Size;
		
		System.out.format("\nThe Sum of Array Items     = %.2f", arrSum);
		System.out.format("\nThe Average of Array Items = %.2f", arrAvg);
	}
}
Enter the Array size = 5
Enter Array 5 elements  = 99 122.5 77 149.90 11

The Sum of Array Items     = 459.40
The Average of Array Items = 91.88

In this Java Program, we created an arrayAverage function that calculates the average of the array items using the do while loop.

package RemainingSimplePrograms;

import java.util.Scanner;

public class AverageofArray3 {
	private static Scanner sc;
	public static void main(String[] args) {
		int Size, i = 0;
		
		sc = new Scanner(System.in);		
		System.out.print("Enter the Array size = ");
		Size = sc.nextInt();
		
		double[] arr = new double[Size];
		
		System.out.format("Enter Array %d elements  = ", Size);
		do 
		{
			arr[i] = sc.nextDouble();
		} while(++i < Size);
		
		System.out.format("\nThe Average of Array Items = %.2f", arrayAverage(arr, Size));
	}
	public static double arrayAverage(double[] arr, int Size) {
		double arrSum = 0, arrAvg = 0;
		int i = 0;
		
		do 
		{
			arrSum = arrSum + arr[i];
		} while(++i < Size);
		
		arrAvg = arrSum / Size;
		return arrAvg;
	}
}
Enter the Array size = 7
Enter Array 7 elements  = 22 99.4 77.12 128 33.7 150 222.9

The Average of Array Items = 104.73