//Cameron Pham CS1A Chapter 8, p. 488, #5
//
/******************************************************************************
* 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 it sorts the months by
* rainfall.
* ______________________________________________________________________________
* INPUT
* Rainfall // Rainfall amount for each month
*
* OUTPUT
* Total rainfall // Total rainfall for the year
* Average rainfall // Average monthly rainfall
*******************************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Initialize Variables
const int MONTHS = 12;
string monthNames[MONTHS] =
{
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
double rainfall[MONTHS]; // Rainfall for each month
double totalRainfall = 0.0; // Total rainfall for the year
double averageRainfall; // Average monthly rainfall
double tempRainfall; // Temporary rainfall value
string tempMonth; // Temporary month name
int maxIndex; // Index of highest rainfall
// Get the rainfall for each month
for (int count = 0; count < MONTHS; count++)
{
cout << "Enter rainfall for " << monthNames[count] << ": ";
cin >> rainfall[count];
// Validate the rainfall amount
while (rainfall[count] < 0)
{
cout << "Rainfall cannot be negative. Enter again: ";
cin >> rainfall[count];
}
totalRainfall += rainfall[count];
}
// Calculate the average monthly rainfall
averageRainfall = totalRainfall / MONTHS;
// Sort rainfall from highest to lowest using selection sort
for (int start = 0; start < MONTHS - 1; start++)
{
maxIndex = start;
for (int count = start + 1; count < MONTHS; count++)
{
if (rainfall[count] > rainfall[maxIndex])
{
maxIndex = count;
}
}
// Swap the rainfall amounts
tempRainfall = rainfall[start];
rainfall[start] = rainfall[maxIndex];
rainfall[maxIndex] = tempRainfall;
// Swap the corresponding month names
tempMonth = monthNames[start];
monthNames[start] = monthNames[maxIndex];
monthNames[maxIndex] = tempMonth;
}
// Display the rainfall statistics
cout << fixed << setprecision(2);
cout << "\nRainfall Statistics" << endl;
cout << "------------------------------" << endl;
cout << "Total rainfall: " << totalRainfall << " inches" << endl;
cout << "Average rainfall: " << averageRainfall << " inches" << endl;
// Display months in descending order of rainfall
cout << "\nMonths Sorted by Rainfall" << endl;
cout << "------------------------------" << endl;
for (int count = 0; count < MONTHS; count++)
{
cout << monthNames[count] << ": "
<< rainfall[count] << " inches" << endl;
}
return 0;
}