In: Computer Science
7. Average Rainfall
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 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 iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period. PSEUDOCODE
PSEUDOCODE:
/*******PseudoCode*******************/
/*
AverageRainFall
{
Main Begin
{
/*Variables initialization*/
years,rfall,total=0,months=0,i,j;
/*prompt the user to read number of
years*/
read years
for i=0 to years
{
for j=0 to
12
{
/*prompt the user to read rainfall of month in
year i*/
read rainfall
/*add rainfall to total*/
total+=rainfall;
/*increment months*/
months++;
}End For
}End For
calculate average as total/months;
print total number of months
print total inches of rainfall
print average rainfall
}End Main
}
Sample source code in c++:
Output:
Code in text format (See above images of code for indentation):
#include <iostream>
using namespace std;
/*main function*/
int main()
{
/*variables*/
int years,rfall,total=0,months=0,i,j;
/*read number of years from user*/
cout<<"Enter the number of years: ";
cin>>years;
/*outer loop iterates for number of years*/
for(i=0;i<years;i++)
{
/*inner loop iterates for 12
months*/
for(j=0;j<12;j++)
{
cout<<"Enter inches of rainfall for month
"<<j+1<<" in year "<<i+1<<": ";
cin>>rfall;
/*calculate
total and increment months*/
total+=rfall;
months++;
}
}
/*print total months*/
cout<<"Total number of months:
"<<months<<endl;
/*print total and average rainfall*/
cout<<"Total inches of rainfall:
"<<total<<endl;
cout<<"Average rainfall per month for the entire
period: "<<(double)total/months;
return 0;
}