Question:
Consider a Math class in which different methods are implemented for advanced mathematical operations. The class has a method named calculateAverage
that calculates the average of a given array of integers. The method takes an array of integers as input and returns the average as a floating-point number.
Write the code for the calculateAverage
method.
public class Math {
public static float calculateAverage(int[] numbers) {
// Write your code here
}
}
Answer:
To calculate the average of an array of integers, we need to sum all the elements in the array and then divide the sum by the number of elements in the array.
Here's the code for the calculateAverage
method:
public class Math {
public static float calculateAverage(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
float average = (float) sum / numbers.length;
return average;
}
}
Let's break down the code:
int
variable sum
and initialize it to 0
. This variable will store the sum of all the elements in the array.for
loop to iterate over each element in the numbers
array.sum
variable.float
variable named average
and calculate the average by dividing the sum
by the number of elements in the array (numbers.length
).average
as the result of the calculateAverage
method.