Write a program that lets the user enter the total rainfall for each of 12 months into an array of doubles.

Write a program that lets the user enter the total rainfall for each of 12 months into an array of doubles.

LANGUAGE: C++

CHALLENGE:

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.

SOLUTION:


#include <iostream>
#include <string>
 
using namespace std;
 
int main(int argc, char *argv[]){
    const int TOTALMONTHS = 12;
    double highest, lowest, getAverage;
    double total = 0;
    double rainfall[TOTALMONTHS];
    string months[TOTALMONTHS] = { "January", "February", "March", "April","May", "June", "July", "August", "September","October", "November", "December" };
  
    for ( int month = 0; month < TOTALMONTHS; month++ ){
        cout << " Enter rainfall for " << months[month] << ": ";
        cin >> rainfall[month];
        total += rainfall[month];
 
        while (rainfall[month] < 0){
            cout << "\nRainfall must be zero or more per month...";
            cout << "\nPlease enter positive amount for " << months[month] << " again: ";
            cin >> rainfall[month];
            total += rainfall[month];
        }
    }
 
    cout << "Total rainfall: \t" << total << endl;
 
    getAverage = total / TOTALMONTHS;
    cout << "Average rainfall: " << getAverage << endl;
 
    string maxMonth, minMonth;
 
    for ( int month = 0; month < TOTALMONTHS; month++ ){
        highest = rainfall[0];
        for ( int count = 0; count < TOTALMONTHS; count++ ){
            if ( rainfall[count] > highest ){
                highest = rainfall[count];
                maxMonth = months[count];
            }
        }
 
        lowest = rainfall[0];
        minMonth = months[0];
 
        for ( int count = 0; count < TOTALMONTHS; count++ ){
            if ( rainfall[count] < lowest ){
                lowest = rainfall[count];
                minMonth = months[count];
            }
        }
    }
 
    cout << "Least rainfall in " << minMonth << endl;
 
    cout << "Most rainfall in " << maxMonth << endl;
    
 
    return 0;
}

Add comment