Java program to calculate average using arrays
Here's a Java program to calculate the average of an array of numbers:
public class ArrayAverage {
public static void main(String[] args) {
double[] numbers = { 1.2, 3.4, 5.6, 7.8, 9.0 };
double sum = 0.0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
double average = sum / numbers.length;
System.out.println("The average of the array is " + average);
}
}
In this program, we first define an array of numbers called numbers. We then loop through the array using a for loop and add up all the values in the array to a variable called sum. We then calculate the average of the array by dividing the sum by the length of the array, and store the result in a variable called average. Finally, we print a message to the console indicating the average value.
You can modify the values in the numbers array to calculate the average of a different set of numbers. Note that if the array is empty, the program will throw a java.lang.ArithmeticException when attempting to divide by zero, so you should add a check to handle this case if necessary.
