Skip to content

Instantly share code, notes, and snippets.

@Elsayegh
Last active August 1, 2018 14:30
Show Gist options
  • Select an option

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

Select an option

Save Elsayegh/e76bf9c9507417daa393fa6d0f29a05a to your computer and use it in GitHub Desktop.
C++ Calculate Values Using Functions and Switch Statements
/*Write a program that determines which of five geographic regions withing a major city (north, south, east, west, central)
had the fewest reported automobile accidents last year. It should have the following functions, which are called by main:
- int getNumAccidents() is passed the name of a region.
It asks the user for the number of automobile accidents reported in that region during the last year,
validates the input, then returns it. It should be called once for each city region.
- void findLowest() is passed the five accident totals.
It determines which is the smallest and prints the name of the region, along with its accident figure.
Input Validation: Do not accept negative values.
*/
#include <iostream>
#include <conio.h>
#include <ctime>
#include <iomanip>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
int getNumAccidents(string);
void findLowest(int, int, int, int, int);
int main() {
int northAcc, southAcc, eastAcc, westAcc, centralAcc;
for (int i = 0; i < 5; i++) {
switch (i)
{
case 0:
northAcc = getNumAccidents("North");
break;
case 1:
southAcc = getNumAccidents("South");
break;
case 2:
eastAcc = getNumAccidents("East");
break;
case 3:
westAcc = getNumAccidents("west");
break;
default:
centralAcc = getNumAccidents("Central");
break;
}
}
findLowest(northAcc, southAcc, eastAcc, westAcc, centralAcc);
_getch();
}
int getNumAccidents(string region) {
int accidents = 0;
cout << "Please enter the number of accidents to the: " << region << endl;
cin >> accidents;
while (accidents < 0) {
cout << "Please enter the number of accidents to the: " << region << endl;
cin >> accidents;
}
return accidents;
}
void findLowest(int north, int south, int east, int west, int central) {
int lowest = 0;
string safestArea = "";
if (north < south && north < east && north < west && north < central) {
lowest = north;
safestArea = "North";
}
else if (south < north && south < east && south < west && south < central) {
lowest = south;
safestArea = "South";
}
else if (east > north && east < south && east < west && east < central) {
lowest = east;
safestArea = "East";
}
else if (west < north && west < south && west < east && west < central) {
lowest = west;
safestArea = "West";
}
else {
lowest = central;
safestArea = "Central";
}
cout << "The region with the lowest accidents is " << safestArea << " With total number of acccidents: " << lowest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment