Skip to content

Instantly share code, notes, and snippets.

@Elsayegh
Created July 27, 2018 20:55
Show Gist options
  • Select an option

  • Save Elsayegh/9c64547e0760feeb7d480e99ea488951 to your computer and use it in GitHub Desktop.

Select an option

Save Elsayegh/9c64547e0760feeb7d480e99ea488951 to your computer and use it in GitHub Desktop.
C++ Challenge
/*Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years.
The program should first ask for the number of years. The outer loop will iterate once for each year.
The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of
rainfall for that month. After all the iterations, the program should display the number of months, the total inches of rainfall
and the average rainfall per month for the entire period.Input validation: Do not accept a number less than 1 for the number of years.
Do not accept negative numbers for the monthly rainfall.*/
#include <iostream>
#include <conio.h>
#include <ctime>
#include <iomanip>
using namespace std;
int main() {
int years = 0;
const int MONTH = 12;
float rainInches = 0.0f;
float totalRainInches = 0.0f;
float averageRainInches = 0.0f;
cout << "How many years need to calculate rain fall average? ";
cin >> years;
while (years < 1) {
cout << "years should be not less than 1 year, please re-enter: ";
cin >> years;
}
for (int i = 1; i <= years; i++) {
for (int months = 1; months <= MONTH; months++) {
cout << "How many inches it rains " << months << " month: ";
cin >> rainInches;
while (rainInches < 0)
{
cout << "Rain inches can't be in negative, please re-enter: ";
cin >> rainInches;
}
totalRainInches += rainInches;
}
}
cout << "\n Number of months: " << years * MONTH << endl;
cout << "Total Rain fall: " << setprecision(2) << fixed << totalRainInches << " Inches" << endl;
cout << "Average rain fall: " << setprecision(2) << fixed << totalRainInches / (years * MONTH) << " Inches" << endl;
_getch();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment