Can someone help program this for me?

Can someone help me translate the program I just wrote into a switch statement?

  • Hey, so I recently wrote a program in C++ for my programming class. The goal was to construct a program where the user inputs one letter (c for car, t for truck, and s for senior) into the program. It will then ask the user how long the vehicle has been parked in the parking garage. Car: First 2 hours = Free Next 3 hours = 0.50\hour next 10 hours = 0.25/hour Truck: First 1 hour = Free Next 2 hours = 1.00/hour next 12 hours = 0.75/hour Senior citizens = No charge I'm just wondering if someone can translate my program which is using If statements into the same program, but using switch statements instead. Here is my program: #include <iostream> using namespace std; int main() { char veh; // vehicle float hrsparked; // hours parked in lot cout << "Please enter your vehicle type. Use letterC for car, letterT for truck, and letterS for senior."; cin >> veh; cout << "Please enter how many hours the vehicle has been parked in the lot:"; cin >> hrsparked; if (veh == 'c') { if (hrsparked<=2) cout << "Free"" << endl; else if (hrsparked <=5) cout << 0.5 * (hrsparked - 2) << endl; else if (hrsparked <=15) cout << 1.50 + (0.25 * (hrsparked - 5)) << endl; else cout <<"error" << endl; } if (veh == 't') { if (hrsparked<=1) cout << "free" << endl else if (hrsparked<=3) cout << 1.00 * (hrsparked - 1) << endl; else if (hrsparked <=15) cout << 2.00 + (0.75 * (hrsparked - 3)) << endl; else cout << "error" << endl; } if (veh == 's') cout << "free" << endl; return 0; }

  • Answer:

    You can do this, it's simple. Put this:     switch (veh) { in front of everything, particularly the first "if" statement, and     } after everything, particularly the last "if" statement. Then take every     if (veh == 'SOMETHING') and change it to     case 'SOMETHING': then put a     break; between each "case" section. That is:     case 'FIRST SOMETHING':     { statements from your original "if" }     break;     case 'SECOND SOMETHING':     etc. etc. etc. It couldn't be easier if I handed you the converted code on a silver platter.

Kevin at Yahoo! Answers Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.