Java Program to Calculate the Average of an Array - The Coding Shala
Home >> Java Programs >> Calculate the Average of an Array
Other Posts You May Like
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
- Java Program to Calculate Simple Interest
- Java Program to Find the Area of Triangle
- Java Program to Find the Factorial of a Number using loop
- Java Program to Calculate the Power of a Number
- Java Program to Calculate the Distance between Two Points
Comments
Post a Comment