Java Program to Calculate the Average of an Array - The Coding Shala

Home >> Java Programs >> Calculate the Average of an Array

 In this post, we will learn how to Calculate the Average of an Array in Java.

Java Program to Calculate the Average of an Array

You have given an integer array, Write a Java program to calculate the average of the given array.

Example 1:
Input: arr = {1,2,3,4,5}
Output: 3

Approach 1

First, find the sum of the given array using the loop, then divide the sum by the length of the array.

Java Program: 

// Java program to Calculate Average of an array

public class Main {
	
	public static void main(String[] args) { 
		
		int[] arr = {1,2,3,4,5};
		
		int sum = 0;
		for (int i = 0; i < arr.length; i++) {
			sum += arr[i];
		}
		
		float avg = sum / arr.length;
		System.out.println("The Average of the Array is: " + avg);
	}
}

Output: 

The Average of the Array is: 3.0


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala