If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To find the average (also known as the arithmetic mean) of a set of numbers in Java, you need to sum up all the numbers and then divide the sum by the total count of numbers. Here's a Java method to calculate the average of an array of integers:
javaCopy code
public class AverageCalculator {
public static double findAverage(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return (double) sum / arr.length;
}
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
double average = findAverage(numbers);
System.out.println("Average: " + average); // Output: 15.0
}
}
In this example, we have a method findAverage
that takes an integer array arr
as an argument. Inside the method, we declare a variable sum
to store the sum of all elements. We use a for-each
loop to iterate through the array and add each element to the sum
variable.
After calculating the sum, we divide it by the length of the array (arr.length
) to get the average. Note that we cast the sum to double
before dividing to ensure that the division is done in floating-point arithmetic, giving us a more precise result.
In the main
method, we demonstrate how to use the findAverage
method with a sample array of numbers. The output will be the average of the numbers, which is 15.0 in this case.
Keep in mind that if the array is empty, you should handle that case separately to avoid division by zero. In the above example, we assume that the array has at least one element to calculate the average.
Comments: 0