In: Computer Science
Zones Crossed --------------------------- Passengers 0 1 2 3 ---------------------------------------- 1 7.50 10.00 12.00 12.75 2 14.00 18.50 22.00 23.00 3 20.00 21.00 32.00 33.00 4 25.00 27.50 36.00 37.00
Sample Run #1 (bold, underlined text is what the user types):
Passengers? 2 Zones? 3 $23 Passengers? 4 Zones? 0 $25 Passengers? -1 Done
c++
Program: In this program, we take user inputs from the user for the number of passengers and zones and depending on that we display the price of the ticket(s) usiing the information. We have implemented it in two ways:
1)Using switch case: For every passenger value we check the value of zones and print the price accordingly.
2)Using a 2D array: In this we store the prices in a 2D array and using the passenger and zones value as indices we access the ticket price.
Implementation using switch case:
Code:
#include <iostream> using namespace std; int main() { //Create variables int zones, passengers; //Take Inputs cout << "Passengers? "; cin >> passengers; //Run a loop while passengers is not equal to -1 while (passengers != -1) { cout << "Zones? "; cin >> zones; //Make switch case for passengers switch (passengers) { case 1: { if (zones == 0) { cout << "$7.5" << endl; } else if (zones == 1) { cout << "$10" << endl; } else if (zones == 2) { cout << "$12" << endl; } else if (zones == 3) { cout << "$12.75" << endl; } break; } case 2: { if (zones == 0) { cout << "$14" << endl; } else if (zones == 1) { cout << "$18.5" << endl; } else if (zones == 2) { cout << "$22" << endl; } else if (zones == 3) { cout << "$23" << endl; } break; } case 3 : { if (zones == 0) { cout << "$20" << endl; } else if (zones == 1) { cout << "$21" << endl; } else if (zones == 2) { cout << "$32" << endl; } else if (zones == 3) { cout << "$33" << endl; } break; } case 4: { if (zones == 0) { cout << "$25" << endl; } else if (zones == 1) { cout << "$27.5" << endl; } else if (zones == 2) { cout << "$36" << endl; } else if (zones == 3) { cout << "$37" << endl; } break; } default: { cout << "Invalid option." << endl; break; } } cout << "Passengers? "; cin >> passengers; } cout << "Done" << endl; return 0; }
Output:
Implementation using a 2D array:
Code:
#include <iostream> using namespace std; int main() { //Store the price of the tickets in a 2D array double price[4][4] = {{7.50, 10.00, 12.00, 12.75}, {14.00, 18.50, 22.00, 23.00}, {20.00, 21.00, 32.00, 33.00}, {25.00, 27.50, 36.00, 37.00}}; //Create variables int zones, passengers; //Take Inputs cout << "Passengers? "; cin >> passengers; //Run a loop while passengers is not equal to -1 while (passengers != -1) { cout << "Zones? "; cin >> zones; //Print for each entry, reduce in the passenger variable by 1 to match array index cout << "$" << price[passengers - 1][zones] << endl; cout << "Passengers? "; cin >> passengers; } cout << "Done" << endl; return 0; }
Output:
#Please ask for any kind of doubts!. Thanks.