The problem is:
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.
my code works, but I'm curious if theres a way of shortening it? I feel like I listed too many variables
int main ()
{
const int MONTHS = 12;
string name[MONTHS]= {"January","February","March","April","May","June","July","August","September","October","November","December"};
int count= 0;
double rain[MONTHS];
double avg;
double year=0;
double highest;
string highMonth;
double lowest;
string lowMonth;
for(count = 0; count < MONTHS; count++) // ask user to enter amount of rainfall for each month
{
cout <<"How many inches of rain does "<< name[count];
cout<< " have? \n";
cin >> rain[count];
while (rain[count] < 0)
{
cout << "Please enter a number greater than 0."<< endl;
cin >> rain[count];
}
}
for(int count=0; count<MONTHS; count++) // totals up all the rainfall
year += rain[count];
avg = year / MONTHS;
for( int count = 0; count < MONTHS; count++) //spits out each month with its amount of rain
{
cout << name[count];
cout<< " has ";
cout<< rain[count] << " inches of rainfall.\n";
}
highest = rain[0]; // finds month with the highest amount of rain
There are some things that can be shortened down yes. For example, you dont need 2 individual for-loops to find the lowest and highest. Here is the full code -
Please always use code tags - use the <> button on the format menu.
The number of variables you have is fine, but I would name them a little differently, for example AverageRainFall, MonthNames, MonthlyRainFall, TotalYearlyRain, HighestMonthlyRain, LowestMonthlyRain. It might seems like overkill for this, but meaningful names are an aid to understanding, can help prevent errors, improve readability etc.
Arrays start at 0, so the for loops should too, otherwise you will miss the first one and have a segmentation fault as it runs past the end of the array.
You can use "\n" instead of std::endl
I like the way you split your std::cout statements over several lines :+) There is no need to put them all into 1 statement.
Hope all goes well :+)
Edit:
Your code would benefit from splitting it into functions - there is an unwritten rule that functions should be less than 40 Lines Of Code (LOC) . This also aids understanding and readability.
So you could have functions for getting the input, Average, lowest, highest, total, showing the output.