Java Array – Average of Elements
Array Average – To find the average of numbers in a Java Array, use a looping technique to traverse through the elements, find the sum of all elements, and divide with number of elements in the array.
In this tutorial, we will learn how to find the average of elements in array, using different looping statements.
Java Integer Array Average using While Loop
In the following program, we will initialize an integer array, and find the average of its elements using Java While Loop.
Java Program
/**
* Java Program - Average of Numbers
*/
public class ArrayAverage {
public static void main(String[] args) {
int numbers[] = {5, 2, 3, 7, 3, 6, 9, 1, 8};
float sum = 0;
int index = 0;
while (index < numbers.length) {
sum += numbers[index];
index++;
}
float average = sum/numbers.length;
System.out.println("Average : " + average);
}
}
Output
Average : 4.888889
Java Float Array Average using For Loop
In the following program, we will initialize a float array, and find the average of its elements using Java For Loop.
Java Program
/**
* Java Program - Average of Numbers
*/
public class ArrayAverage {
public static void main(String[] args) {
float numbers[] = {0.5f, 1.2f, 0.3f, 0.7f, 0.3f, 1.6f, 1.9f, 0.1f, 2.8f};
float sum = 0;
for (int index = 0; index < numbers.length; index++) {
sum += numbers[index];
}
float average = sum/numbers.length;
System.out.println("Average : " + average);
}
}
Output
Average : 1.0444444
Java Double Array Average using For-each Loop
In the following program, we will initialize a double array, and find the average of its elements using Java For-each Loop.
Java Program
/**
* Java Program - Average of Numbers
*/
public class ArrayAverage {
public static void main(String[] args) {
double numbers[] = {0.5, 1.2, 0.3, 0.7, 0.3, 1.6, 1.9, 0.1, 2.8};
double sum = 0;
for (double number: numbers) {
sum += number;
}
double average = sum/numbers.length;
System.out.println("Average : " + average);
}
}
Output
Average : 1.0444444444444443
Conclusion
Concluding this Java Tutorial, we learned how to find Average of a Java Array with some of the combinations of numeric datatypes for array elements and looping technique. You may use any looping technique on any of the numeric datatypes and find the Java Array average.