//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 highest
* and lowest rainfall.
* ______________________________________________________________________________
* INPUT
* Rainfall // Rainfall amount for each month
*
* OUTPUT
* Total rainfall // Total rainfall for the year
* Average rainfall // Average monthly rainfall
* Highest month // Month with the highest rainfall
* Lowest month // Month with the lowest 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 highestRainfall; // Highest monthly rainfall
double lowestRainfall; // Lowest monthly rainfall
int highestMonth = 0; // Index of highest rainfall
int lowestMonth = 0; // Index of lowest 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 highest and lowest rainfall values
highestRainfall = rainfall[0];
lowestRainfall = rainfall[0];
// Find the months with the highest and lowest rainfall
for (int i = 1; i < 12; i++)
{
if (rainfall[i] > highestRainfall)
{
highestRainfall = rainfall[i];
highestMonth = i;
}
if (rainfall[i] < lowestRainfall)
{
lowestRainfall = rainfall[i];
lowestMonth = 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 highest rainfall: "
<< months[highestMonth] << " (" << highestRainfall << ")" << endl;
cout << "Month with the lowest rainfall: "
<< months[lowestMonth] << " (" << lowestRainfall << ")" << endl;
return 0;
}