Post

Created by @nathanedwards
 at November 4th 2023, 9:22:06 pm.

AP Computer Science Exam Question: Parameters and Return Values

Consider the following scenario:

You are tasked with creating a program that calculates the average temperature for a given set of days. You need to design a method calculateAverageTemperature with the following specifications:

Method Signature:

public static double calculateAverageTemperature(int[] temperatures)

Parameters:

  • temperatures: An array of integers representing the temperature values for each day.

Return Value:

  • Returns a double value representing the average temperature.

Complete the method calculateAverageTemperature by implementing the following steps:

  1. Initialize a variable sum to 0 to store the sum of all temperatures.
  2. Use a for-each loop to iterate over each temperature value in the temperatures array.
  3. Within the loop, add each temperature value to the sum variable.
  4. After the loop, calculate the average temperature by dividing the sum by the total number of temperatures in the array. Store the result in a variable average.
  5. Return the average value as the result.

Write the complete code for the calculateAverageTemperature method and provide the step-by-step explanation for each step.

public static double calculateAverageTemperature(int[] temperatures) {
    // Step 1: Initialize a variable to store the sum
    int sum = 0;
    
    // Step 2: Use a for-each loop to iterate over temperatures
    for (int temperature : temperatures) {
        // Step 3: Add each temperature to the sum
        sum += temperature;
    }
    
    // Step 4: Calculate the average temperature
    double average = (double) sum / temperatures.length;
    
    // Step 5: Return the average temperature
    return average;
}

Explanation:

  1. In step 1, we initialize the sum variable to 0, which will be used to store the sum of all temperature values.
  2. In step 2, we use a for-each loop to iterate over each temperature value in the temperatures array. This loop assigns each value to the variable temperature.
  3. In step 3, we add each temperature value to the sum variable. This is done by using the += operator, which adds the value on the right-hand side to the current value of sum.
  4. After the loop finishes, in step 4, we calculate the average temperature by dividing the sum by the total number of temperature values in the array (temperatures.length). We cast sum to a double to ensure floating-point division.
  5. Finally, in step 5, we return the calculated average temperature as the result of the method.

This method calculates the average temperature of a given set of days by summing all the temperature values and dividing it by the total number of values in the array.