How To Calculate the Average of an Array in Java


Question mark

This is one of the articles from our Java Tutorial for Beginners.


1. Create 2 arrays made of 5 integer numbers randomly chosen from the range 0 to 5.

2. Display the arrays in the console in two separate lines.

3. Calculate the average of the numbers of each array and then display a message that states which array has a larger average. However, if the two arrays have the same average, the message needs to say that they are the same.



We create two arrays of 5 randomly chosen integer numbers in the range 0 to 5.

We create a loop that will generate elements of the arrays. We generate numbers in the range 0 to 5. If you've forgotten how to generate numbers in Java, read this article: "Random Number Generation in Java"

We display each array in a line with the help of the Arrays class.

We create variables to store the averages of the arithmetic arrays.

We find the sum of the elements of each array and then divide each sum by the number of elements in each array. We do this to find the average of each array.

We compare the averages and then display the correct phrase in the console.

You can find more articles in our Java Tutorial for Beginners.


Самоучители--узнать детальнее--