Write a Java Program to Calculate Average Using Arrays

Calculating the average of a set of numbers is a common task in programming.

Java provides an easy way to do this using arrays.

In this tutorial, we’ll look at how to calculate the average of numbers using arrays in Java.


To start, we’ll create an array of numbers.

Let’s say we have an array of integers called “numbers”.

int[] numbers = {2, 4, 6, 8, 10};

Next, we’ll calculate the sum of all the numbers in the array.

We can do this by looping through the array and adding each number to a variable called “sum”.

int sum = 0;
for(int i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}

Now that we have the sum of the numbers in the array, we can calculate the average by dividing the sum by the number of elements in the array.

We can get the number of elements in the array using the “length” property.

double average = (double)sum / numbers.length;

Notice that we cast “sum” to a double before dividing it by “numbers.length”.

This is because we want to get a decimal value for the average, not an integer value.

Finally, we can print the average to the console using the “System.out.println()” method.

System.out.println("The average is: " + average);

Here’s the full program:

public class AverageCalculator {
    public static void main(String[] args) {
        int[] numbers = {2, 4, 6, 8, 10};
        int sum = 0;
        for(int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        double average = (double)sum / numbers.length;
        System.out.println("The average is: " + average);
    }
}

When we run this program, we’ll get the following output:

The average is: 6.0

That’s all there is to it!

Using arrays to calculate the average of a set of numbers in Java is a simple and straightforward process.