find the average of all elements in an array in java
Code snippet on how to find the average of all elements in an array in java
public static double getAverage(int[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = sum / arr.length;
return average;
}
This code takes in an array of integers as an argument and finds the average of all the elements. It first creates a double called ‘sum’ and initializes it to 0. It then uses a for loop to iterate through the array and adds each element to the ‘sum’ variable. After looping through the array, it will take the total ‘sum’ and divide by the length of the array to generate the average. Finally, the average is returned.