Related questions with answers
Write a program that lets the user enter the total rainfall for each of 12 months into an array of doubles. The program should calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and lowest amounts. Input Validation: Do not accept negative numbers for monthly rainfall figures.
Solutions
VerifiedBy using C++, we write a program. that displays the following after taking the required data from user:
-
The total rainfall for the year.
-
The average monthly rainfall.
-
The month (displayed as a string) with the highest amount of rainfall.
-
The month (displayed as a string) with the lowest amount of rainfall.
We use for loop to read values into an array from the user and then use while loop for each value read to validate input. Then loop again on the array to find the lowest and highest monthly rainfalls using if statements. For each element looped on, add it to the accumulator variable total. Get the monthly average by dividing the total by and typecasting to double to prevent integer division.
#include <iostream>
using namespace std;
int main(){
const int MONTHS = 12;
double rainfall[MONTHS];
// get the total rainfall from user for each month
for(unsigned i=0;i<MONTHS;i++){
cout<<"Please enter the total rainfall of month ["<<(i+1)<<"]\n";
cout<<"Total rainfall is : ";
cin>>rainfall[i];
// perform input validation
while(rainfall[i]<0){
// as long as the value is less than 0, i.e. negative
// ask user to enter it again
cout<<"The value should not be negative.\n";
cout<<"Enter the rainfall again : ";
cin>>rainfall[i];
}
}
// now compute statistics
double total,avg;
unsigned highestMonth,lowestMonth;
// total is the sum of all rainfalls
// avg = total/12
// initialize highestMonth & lowestMonth to the first
highestMonth = lowestMonth = 0;
// initialize total with 0
total = 0.0;
Create an account to view solutions
Create an account to view solutions
Recommended textbook solutions

Computer Organization and Design MIPS Edition: The Hardware/Software Interface
5th Edition•ISBN: 9780124077263 (5 more)David A. Patterson, John L. Hennessy
Starting Out with C++ from Control Structures to Objects
8th Edition•ISBN: 9780133769395 (10 more)Godfrey Muganda, Judy Walters, Tony Gaddis
Fundamentals of Database Systems
7th Edition•ISBN: 9780133970777 (1 more)Ramez Elmasri, Shamkant B. Navathe
Introduction to Algorithms
3rd Edition•ISBN: 9780262033848 (2 more)Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. CormenMore related questions
1/2
1/3