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 find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala