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 and the for loop will iterate each array item and add it to the arrSum variable. Next, we are diving into 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 AvgofAr2 {
	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 size = ");
		Size = sc.nextInt();
		
		double[] arr = new double[Size];
		
		System.out.format("Enter %d elements  = ", Size);
		while(i < Size) {
			arr[i] = sc.nextDouble();
			arrSum = arrSum + arr[i];
			i++;
		}
		
		arrAvg = arrSum / Size;
		
		System.out.format("\nThe Sum     = %.2f", arrSum);
		System.out.format("\nThe Average = %.2f", arrAvg);
	}
}
Enter the Size = 5
Enter 5 elements  = 99 122.5 77 149.90 11

The Sum     = 459.40
The Average = 91.88

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

package RemainingSimplePrograms;

import java.util.Scanner;

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

The Average = 104.73