Question:
A math class instructor wants to implement a method called findAverage
in their Math class to calculate the average of a list of numbers. The method should take in a list of integers as a parameter and return the average of the numbers in the list as a floating-point number.
Write the code for the findAverage
method in the Math class using an intermediate level coding techniques in Java. Make sure to include the method signature.
Math.java
public class Math {
// Write the findAverage method here
}
Answer:
Math.java
public class Math {
public static double findAverage(int[] numbers) {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return (double) sum / numbers.length;
}
}
Explanation:
The method findAverage
takes an array of integers numbers
as a parameter and calculates the sum of all the numbers in the array using a for-each loop. It initializes a variable sum
to 0 and iterates over each element number
in the numbers
array, adding it to the sum
.
After calculating the sum, it returns the average of the numbers by dividing the sum by the length of the numbers
array, casting the result to a double
to obtain the desired floating-point representation of the average.
For example, if we have the array [2, 4, 6, 8, 10]
, the sum would be 2 + 4 + 6 + 8 + 10 = 30
, and the average would be 30 / 5 = 6.0
.