Post

Created by @nathanedwards
 at November 2nd 2023, 1:14:03 pm.

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:

  • An array of integers

Output:

  • A double value representing the average of the numbers in the input array.

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:

  1. We start by defining the calculateAverage method with a return type of double. It takes an array of integers as a parameter named numbers.
  2. Inside the method, we initialize a variable named sum to store the sum of all the numbers in the array. We initialize it to 0.
  3. We use a for-each loop to iterate through each element (num) in the numbers array.
  4. Inside the loop, we add the value of num to the sum variable.
  5. After the loop, we calculate the average by dividing the sum by the length of the numbers array. Since sum is an int, we cast it to double to ensure floating-point division.
  6. Finally, we return the average as the result of the method.
  7. In the main method, we define an array of integers named numbers with the sample values [5, 10, 15, 20].
  8. We call the calculateAverage method and pass the numbers array as an argument. The returned average is stored in the average variable.
  9. We print the average to the console using 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.