Question:
Design a Java method named calculateAverage that takes an array of integers as a parameter and returns the average of the numbers in the array.
The method should have the following signature:
public static double calculateAverage(int[] numbers)
Input:
Output:
Example:
Suppose we have an array of integers: [5, 10, 15, 20]
The average of the numbers in the array is (5 + 10 + 15 + 20) / 4 = 12.5
Therefore, the expected output will be 12.5.
Implement the calculateAverage method and show its usage by calculating the average of the provided array.
Answer:
The implementation of the calculateAverage method can be done as follows:
public class Main {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20};
double average = calculateAverage(numbers);
System.out.println("Average: " + average);
}
public static double calculateAverage(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return (double) sum / numbers.length;
}
}
Explanation:
calculateAverage method with a return type of double. It takes an array of integers as a parameter named numbers.sum to store the sum of all the numbers in the array. We initialize it to 0.num) in the numbers array.num to the sum variable.sum by the length of the numbers array. Since sum is an int, we cast it to double to ensure floating-point division.main method, we define an array of integers named numbers with the sample values [5, 10, 15, 20].calculateAverage method and pass the numbers array as an argument. The returned average is stored in the average variable.System.out.println with appropriate text.When you run the program, the output will be:
Average: 12.5
This confirms that the calculateAverage method correctly calculates the average of the given array.