Post

Created by @nathanedwards
 at November 1st 2023, 5:00:07 pm.

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:

  1. We declare an int variable sum and initialize it to 0. This variable will store the sum of all the elements in the array.
  2. We use a for loop to iterate over each element in the numbers array.
  3. Inside the loop, we add the current element to the sum variable.
  4. After the loop, we declare a float variable named average and calculate the average by dividing the sum by the number of elements in the array (numbers.length).
  5. Finally, we return the average as the result of the calculateAverage method.