//Cameron Pham CS1A Chapter 7, p. 444, #2
//
/******************************************************************************
* CALCULATE RAINFALL STATISTICS
* ______________________________________________________________________________
* This program accepts a double value for the total rainfall for each of 12
* months and stores the value in an array of doubles. It calculates and displays
* the total rainfall, average monthly rainfall, and months with the greatest
* and Least rainfall.
* ______________________________________________________________________________
* INPUT
* Rainfall // Rainfall amount for each month
*
* OUTPUT
* Total rainfall // Total rainfall for the year
* Average rainfall // Average monthly rainfall
* Greatest month // Month with the Greatest rainfall
* Least month // Month with the Least rainfall
*******************************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Initialize variables
double rainfall[12]; // Stores rainfall for 12 months
double totalRainfall = 0.0; // Total rainfall for the year
double averageRainfall; // Average rainfall per month
double greatestRainfall; // greatest monthly rainfall
double LeastRainfall; // Least monthly rainfall
int greatestMonth = 0; // Index of greatest rainfall
int leastMonth = 0; // Index of Least rainfall
// Store the names of the 12 months
string months[12] =
{
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
// Ask the user to enter rainfall for each month
for (int i = 0; i < 12; i++)
{
cout << "Enter the rainfall for " << months[i] << ": ";
cin >> rainfall[i];
// Validate the input
while (rainfall[i] < 0)
{
cout << "Error: Rainfall cannot be negative. ";
cout << "Enter the rainfall for " << months[i] << " again: ";
cin >> rainfall[i];
}
// Add the monthly rainfall to the annual total
totalRainfall += rainfall[i];
}
// Initialize the greatest and Least rainfall values
greatestRainfall = rainfall[0];
LeastRainfall = rainfall[0];
// Find the months with the greatest and Least rainfall
for (int i = 1; i < 12; i++)
{
if (rainfall[i] > greatestRainfall)
{
greatestRainfall = rainfall[i];
greatestMonth = i;
}
if (rainfall[i] < LeastRainfall)
{
LeastRainfall = rainfall[i];
LeastMonth = i;
}
}
// Calculate the average monthly rainfall
averageRainfall = totalRainfall / 12.0;
// Display the rainfall statistics
cout << fixed << setprecision(2);
cout << endl << "Rainfall Statistics for the Year" << endl;
cout << "--------------------------------" << endl;
cout << "Total rainfall: " << totalRainfall << endl;
cout << "Average monthly rainfall: " << averageRainfall << endl;
cout << "Month with the greatest rainfall: "
<< months[greatestMonth] << " (" << greatestRainfall << ")" << endl;
cout << "Month with the least rainfall: "
<< months[LeastMonth] << " (" << LeastRainfall << ")" << endl;
return 0;
}