public class AverageArray {
public static void main(String[] args) {
int[] arr = {5, 1, 9, 14, 25};
int n = arr.length;
double sum = 0.0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
double avg = sum / n;
System.out.println("The average of the array is: " + avg);
}
}
The average of the array is: 10.8
arr
and initialize it with the example values {5, 1, 9, 14, 25}
. We get the length of the array n
and declare a double
variable sum to store the sum of all the elements in the array.for
loop to iterate through the array and add each element to the sum
variable. We then calculate the average of the array by dividing the sum
by the n
and storing it in a double
variable avg
.System.out.println()
.