Post

Created by @nathanedwards
 at November 24th 2023, 8:11:56 pm.

Question:

Write a Java method called 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)

Assume that the input array is not null and contains at least one element.

Provide the implementation of the calculateAverage method and an example usage of the method in the main method.

Answer:

public class AverageCalculator {
    public static void main(String[] args) {
        int[] exampleArray = {10, 20, 30, 40, 50};
        double average = calculateAverage(exampleArray);
        System.out.println("Average: " + average);
    }

    public static double calculateAverage(int[] numbers) {
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        return (double) sum / numbers.length;
    }
}

Explanation:

The calculateAverage method takes an array of integers as a parameter and returns the average of the numbers in the array.

  • In the main method, an example array exampleArray is created and assigned some values.

  • The calculateAverage method is called with exampleArray as the argument, and the result is stored in the average variable.

  • Within the calculateAverage method, a variable sum is initialized to 0.

  • Then, a for-each loop is used to iterate through each element of the numbers array. For each element, its value is added to the sum.

  • After the loop, the average is calculated by dividing the sum by the length of the array, and the result is cast to a double to ensure accurate division.

  • The calculated average is then returned.

Therefore, the output of the main method would be:

Average: 30.0