get the average of an array in java

‮ptth‬s://www.lautturi.com
get the average of an array in java

To calculate the average of an array of numbers in Java, you can use a for loop to iterate through the array and calculate the sum of all the elements. Then, you can divide the sum by the length of the array to get the average. Here's an example of how you could do this:

double[] numbers = {1.0, 2.0, 3.0, 4.0, 5.0};
double sum = 0.0;
for (double number : numbers) {
  sum += number;
}
double average = sum / numbers.length;
System.out.println("The average is: " + average);

This code will output "The average is: 3.0".

Alternatively, you can use the IntStream.average() method from the Java Stream API to calculate the average of an array of integers. Here's an example of how you could use this method:

int[] numbers = {1, 2, 3, 4, 5};
double average = IntStream.of(numbers).average().getAsDouble();
System.out.println("The average is: " + average);

This code will also output "The average is: 3.0".

Created Time:2017-11-01 12:04:59  Author:lautturi