Introduce Java How To Find the Average of Array Elements and give examples
In Java, an array is a collection of elements of the same type, stored in contiguous memory locations. To find the average of the elements in an array, you need to follow these steps:
The average can be calculated using the formula:
[ \text{Average} = \frac{\text{Sum of elements}}{\text{Number of elements}} ]
Here’s a simple Java program that demonstrates how to find the average of array elements:
public class AverageOfArray {
public static void main(String[] args) {
// Example array
double[] numbers = {10.5, 20.0, 30.5, 40.0, 50.5};
// Calculate the average
double average = calculateAverage(numbers);
// Print the result
System.out.println("The average of the array elements is: " + average);
}
public static double calculateAverage(double[] array) {
double sum = 0.0;
// Calculate the sum of the array elements
for (double num : array) {
sum += num;
}
// Calculate the average
return sum / array.length;
}
}
double
values named numbers
.calculateAverage
method, passing the numbers
array as an argument.calculateAverage
method, we initialize a variable sum
to 0. We then use a for-each loop to iterate through each element in the array, adding each element to sum
.array.length
) to get the average.When you run the above program, the output will be:
The average of the array elements is: 30.5
Here’s another example using an integer array:
public class AverageOfIntArray {
public static void main(String[] args) {
// Example integer array
int[] numbers = {1, 2, 3, 4, 5};
// Calculate the average
double average = calculateAverage(numbers);
// Print the result
System.out.println("The average of the array elements is: " + average);
}
public static double calculateAverage(int[] array) {
double sum = 0.0;
// Calculate the sum of the array elements
for (int num : array) {
sum += num;
}
// Calculate the average
return sum / array.length;
}
}
When you run this program, the output will be:
The average of the array elements is: 3.0
Finding the average of array elements in Java is straightforward. By summing the elements and dividing by the number of elements, you can easily compute the average. This concept can be applied to arrays of any numeric type, such as int
, float
, or double
.