In: Computer Science
Design 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 numbers of years. The outer loop
will iterate once for each year. The inner loop will iterate twelve
times, once for each month. After all iterations, the program
should display the number of months, the total inches of rainfall,
and the average rainfall per month for the entire period.
// C++ program to collect data using nested loops and calculate the average rainfall over a period of years
#include <iostream>
using namespace std;
int main() {
int years;
double rainfall, total_rainfall = 0;
// input of number of years
cout<<"Enter the number of years : ";
cin>>years;
// nested loops to input data of rainfall for the years
for(int i=1;i<=years;i++)
{
for(int j=1;j<=12;j++)
{
cout<<"Enter inches of rainfall for year-"<<i<<" month-"<<j<<" : ";
cin>>rainfall;
total_rainfall += rainfall; //calculate the total rainfall
}
}
// output
cout<<"\nNumber of months :"<<(years*12)<<endl; // number of months
cout<<"Total inches of rainfall : "<<total_rainfall<<endl; // total inches of rainfall
cout<<"Average rainfall per month for the entire period : "<<(total_rainfall/(years*12))<<endl; // average rainfall per month for the entire period.
return 0;
}
//end of program
Output: