- 27th Mar 2023
- 08:24 am
- Admin
C++ Homework Help -
C++: Calculating Average Rainfall (Nested For loops) - Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all the iterations, the program should display the number of months, the total inches of rainfall and the average rainfall per month for the entire period. Input validation: Do not accept a number less than 1 for the number of years. Do not accept negative numbers for the monthly rainfall.
C++ Homework Solution
#include
using namespace std;
int main()
{
int years;
double rainfall, totalRainfall = 0.0, averageRainfall;
int numMonths = 12; // fixed number of months in a year
// ask the user for the number of years
cout << "Enter the number of years: ";
cin >> years;
// input validation for number of years
while (years < 1)
{
cout << "Invalid input. Enter the number of years (must be greater than 0): ";
cin >> years;
}
// nested loops to collect data and calculate the average rainfall
for (int i = 1; i <= years; i++)
{
cout << "Year " << i << endl;
for (int j = 1; j <= numMonths; j++)
{
cout << "Enter the inches of rainfall for month " << j << ": ";
cin >> rainfall;
// input validation for monthly rainfall
while (rainfall < 0)
{
cout << "Invalid input. Enter the inches of rainfall for month " << j << " (must be greater than or equal to 0): ";
cin >> rainfall;
}
totalRainfall += rainfall;
}
}
// calculate the average rainfall per month for the entire period
averageRainfall = totalRainfall / (years * numMonths);
// display the results
cout << endl;
cout << "Number of months: " << years * numMonths << endl;
cout << "Total inches of rainfall: " << totalRainfall << endl;
cout << "Average rainfall per month: " << averageRainfall << " inches" << endl;
return 0;
}
In this solution, we first ask the user for the number of years, and use a while loop for input validation to make sure the number of years is at least 1. We then use nested loops to collect data and calculate the average rainfall. The outer loop iterates once for each year, and the inner loop iterates 12 times for each month. We ask the user for the inches of rainfall for each month, and use another while loop for input validation to make sure the monthly rainfall is not negative. We keep track of the total rainfall for all the years and months, and then calculate the average rainfall per month for the entire period. Finally, we display the results to the user, including the number of months, the total inches of rainfall, and the average rainfall per month.