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:
Complete the method calculateAverageTemperature
by implementing the following steps:
sum
to 0 to store the sum of all temperatures.temperatures
array.sum
variable.sum
by the total number of temperatures in the array. Store the result in a variable average
.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:
sum
variable to 0, which will be used to store the sum of all temperature values.temperatures
array. This loop assigns each value to the variable temperature
.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
.sum
by the total number of temperature values in the array (temperatures.length
). We cast sum
to a double
to ensure floating-point division.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.