Post

Created by @nathanedwards
 at October 31st 2023, 2:45:12 pm.

AP Computer Science Exam Question

Instructions:

Write a Java program that implements a method called calculateAverage that takes an array of integers as a parameter and returns the average of all the integers in the array. The method should be declared as follows:

public static double calculateAverage(int[] numbers)

In your main method, create an array containing the following integers: [5, 10, 15, 20, 25]. Call the calculateAverage method passing the array as an argument and store the returned result in a variable called average. Finally, print the value of average to the console.

Example Output:

The average is: 15.0

Code Explanation:

To compute the average, we need to sum all the integers in the array and then divide the sum by the total number of elements in the array. Here's the step-by-step explanation of the solution:

  1. Define the calculateAverage method with a return type of double and a single parameter of type int[] named numbers.

  2. Inside the calculateAverage method, declare a variable named sum of type int and initialize it to 0. This variable will be used to sum the elements in the array.

  3. Use a for-each loop to iterate over each element num in the numbers array.

  4. Inside the loop, add the current element num to the sum variable.

  5. After the loop, calculate the average by dividing the sum variable by the length of the numbers array and store the result in a variable called average of type double.

  6. Return the value of average from the calculateAverage method.

  7. In the main method, create an array of integers called numbers and initialize it with the values [5, 10, 15, 20, 25].

  8. Call the calculateAverage method, passing the numbers array as an argument, and store the returned result in a variable called average.

  9. Print the value of average to the console using the System.out.println method.

Solution:

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

    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20, 25};
        double average = calculateAverage(numbers);
        System.out.println("The average is: " + average);
    }
}

Make sure to save this code in a file named AverageCalculator.java and run it to see the expected output.