Google News
logo
Java Program to Calculate Average Using Arrays
In the following example of Java program to calculate the average of an array using arrays :
Program :
public class AverageArray {
    public static void main(String[] args) {
        int[] arr = {5, 1, 9, 14, 25};
        int n = arr.length;
        double sum = 0.0;
        for (int i = 0; i < n; i++) {
            sum += arr[i];
        }
        double avg = sum / n;
        System.out.println("The average of the array is: " + avg);
    }
}
Output :
The average of the array is: 10.8
In this program, we first declare an integer array arr and initialize it with the example values {5, 1, 9, 14, 25}. We get the length of the array n and declare a double variable sum to store the sum of all the elements in the array.

We use a for loop to iterate through the array and add each element to the sum variable. We then calculate the average of the array by dividing the sum by the n and storing it in a double variable avg.

Finally, we print the average of the array to the console using System.out.println().