Lab 4
"All programmers are playwrights, and all computers are lousy actors." - Anonymous
Cover Topics
Switch Statements
Basic Debugging
Lab Materials
// PreLab 4 Assignment
// The following is an extremely scientific personality test that can predict
// how well you will do in this course.
// Fill in the area below with the requested code.
#include <iostream>
using namespace std;
int main()
{
char answer;
string message;
cout << "Is Star Trek better than Star Wars? ('Y' or 'N')" << endl;
cin >> answer;
// TODO - Change the following IF-ELSE statement to an
// equivalent switch statement.
if (answer == 'y' || answer == 'Y')
{
cout << "You think Star Trek is better than Star Wars..." << endl;
message = "Wrong! You are likely to fail this class...";
}
else if (answer == 'n' || answer == 'N')
{
cout << "You do not think think Star Trek is better than Star Wars..." << endl;
message = "Correct! You will undoubtedly ace this class!!!!" ;
}
else
{
message = "Invalid Input. This does not bode well for you.";
}
cout << message << endl;
return 0;
}
Prelab 4 Reading
Lab Content
Review If/Else Statements
#include <iostream> #include <iomanip> using namespace std; int main() { char letter_grade; float GPA; letter_grade = 'B'; if(letter_grade == 'A') { GPA = 4.0; } else if (letter_grade == 'B')
{ GPA = 3.0; } else if (letter_grade == 'C')
{ GPA = 2.0; } else if (letter_grade == 'D')
{ GPA = 1.0; } else if (letter_grade == 'F') { GPA = 0.0; } else { cout << "invalid input" << endl; } cout << "Using IF Statements : " << setprecision(1) << fixed << GPA << endl; return 0; }
Switch Statement Syntax
Switch syntax is as follows:
switch (expression)
{
case expression:
// statements
break;
}
The switch's expression is compared to each case's expression. If the expressions are equal to each other it will execute any statements that follow the case, until hitting a break statement. Break statements tell the program to leave the switch statement and continue with the code after it.
Switch statements function similarly to an IF-ELSE statement. The following can be rewritten as a switch statement.
#include <iostream> #include <iomanip> using namespace std; int main() { // This switch statement does the same thing as the above IF-ELSE IF code. char letter_grade = 'B';
float GPA; switch (letter_grade) { case 'A': GPA = 4.0; break; // break statements signal to leave the switch statement case 'B': GPA = 3.0; break; case 'C': GPA = 2.0; break; case 'D': GPA = 1.0; break; default: // default is like an else statement cout << "invalid input" << endl; break; } cout << "Using Switch Statement : " << setprecision(1) << fixed << GPA << endl; return 0; }
Multiple Cases to a Break
How do you allow for case sensitive user input? One can create multiple cases assigned to execute the same code. In this example, both an upper case and lower case letter will execute the same thing.
#include <iostream> #include <iomanip> using namespace std; int main() { char letter_grade = 'b';
float GPA; switch (letter_grade) { case 'A': // same as if(letter_grade == 'A' || letter_grade == 'a') case 'a': GPA = 4.0; break; case 'B': case 'b': GPA = 3.0; break; case 'C': case 'c': GPA = 2.0; break; case 'D': case 'd': GPA = 1.0; break; default: //default is like an else statement cout << "invalid input" << endl; break; } cout << "Using Lower Case Input : " << setprecision(1) << fixed << GPA << endl; return 0; }
Disadvantages of a Switch Statement
There are a few instances where switch statements may not be the best option to choose. Take for example, ranges. You cannot easily implement a range with a switch statement. The only possible way to do this is to list out each case individually. With bounded ranges, this is possible, if tedious and lengthy. However, with unbounded ranges this is impossible because there are infinite numbers within that range. An example of implementing a range with a switch statement is shown below.Another example of an instance where you may not want to use switch statements is when you are using datatypes other than characters or integers. Switch statements work correctly only when using integer and character data types, so if you are using others, you may want to consider other options.
Finally, switch statements are not flexible enough to compare multiple variables at once.
#include <iostream> using namespace std; int main() { // Consider the following if...else statement int num = 85; if(num <= 89 && num >= 80) { cout << "Your letter grade is a B (If Statement)" << endl; } else { cout << "out of range" << endl; } // This is the same logic but in a switch statement. Notice how many cases are necessary. switch(num) { case 89: case 88: case 87: case 86: case 85: case 84: case 83: case 82: case 81: case 80: cout << "your letter grade is a B (Switch Statment)" << endl; break; default: cout << "out of range" << endl; break; } return 0; }
Practical Example
This example shows an application of switch statements. Notice the nested switch statements. Style here is particularly important for readability. Also, please take note of the break statement at the end of the nested switch. Every case must be paired with a break unless it is logically unnecessary.
#include <iostream> #include <cmath> using namespace std; int main() { // Another example of a case statement. Can you read it? As you can // see, as programs get more complex using good style is crucial for // readability. const double PI = 3.14159; int choice_A; int choice_B; double total; // title menu // cout << "\n\nWelcome to my shape calculator!" << endl << endl << "Please select one of the following" << endl << "1. Circle" << endl << "2. Square " << endl; cin >> choice_A; switch(choice_A) { // Circle Selected // case 1: // Take radius and desired calculation from the user // double radius; cout << "You have selected Circle!" << endl << endl << "Please enter the radius of your circle" << endl; cin >> radius; cout << "Please select one of the following" << endl << "1. Area" << endl << "2. Circumference" << endl; cin >> choice_B; // Calculate the area or the circumference // switch(choice_B) { case 1: total = PI * pow(radius, 2.0); cout << "The Area is " << total << endl; break; case 2: total = PI * 2 * radius; cout << "The Circumference is " << total << endl; break; default: cout << "invalid input. Terminating the program." << endl; break; } break; // NOTICE: This break statement is necessary because it signifies the end of "case 1:"
// or the end of the circle case. // Square Selected // case 2: double length; cout << "You have selected Square!" << endl << endl << "Please enter the length of a side." << endl; cin >> length; cout << "Please select one of the following" << endl << "1. Area" << endl << "2. Perimeter" << endl; cin >> choice_B; switch(choice_B) { case 1: total = pow(length, 2.0); cout << "The Area is " << total; break; case 2: total = length * 4; cout << "The Perimeter is " << total; break; default: cout << "Invalid input. Terminating the program." << endl; break; } break; default: cout << "Invalid input. Terminating the program." << endl; break; } return 0; }
For reference, here is the same program as above, but with nested if statements.
#include <iostream>
#include <cmath>
using namespace std; int main()
{
const double PI = 3.14159; int choice_A;
int choice_B;
double total;
// title menu //
cout << "\n\nWelcome to my shape calculator!" << endl << endl
<< "Please select one of the following" << endl
<< "1. Circle" << endl
<< "2. Square " << endl; cin >> choice_A; if(choice_A == 1) // Circle Selected //
{
// Take radius and desired calculation from the user //
double radius;
cout << "You have selected Circle!" << endl << endl
<< "Please enter the radius of your circle" << endl;
cin >> radius;
cout << "Please select one of the following" << endl
<< "1. Area" << endl
<< "2. Circumference" << endl;
cin >> choice_B;
// Calculate the area or the circumference //
if(choice_B == 1)
{
total = PI * pow(radius, 2.0);
cout << "The Area is " << total << endl;
}
else if(choice == 2)
{
total = PI * 2 * radius;
cout << "The Circumference is " << total << endl;
}
else
{
cout << "Invalid Input. Terminating the program." << endl;
}
}
else if(choice_A == 2) // Square Selected //
{
double length;
cout << "You have selected Square!" << endl << endl
<< "Please enter the length of a side." << endl;
cin >> length;
cout << "Please select one of the following" << endl
<< "1. Area" << endl
<< "2. Perimeter" << endl;
cin >> choice_B;
if(choice_B == 1)
{
total = pow(length, 2.0);
cout << "The Area is " << total << endl;
}
else if(choice == 2)
{
total = length * 4;
cout << "The Perimeter is " << total;
}
else
{
cout << "Invalid Input. Terminating the program." << endl;
}
}
else
{
cout << "Invalid input. Terminating the program." << endl;
}
return 0;
}
Basics of Debugging a C++ Program
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { // ---------------------- Basics of Debugging --------------------------------- // There are two problems with the below code. It may be difficult to // initially see, so lets add a debugging 'cout' to help us see // what is going wrong. // ** Note - ALWAYS end a debugging statement with an 'endl'! ** // ** Because of how the cout buffer works, if you don't ** // ** add 'endl' it may not print the message if your ** // ** program crashes prematurely. ** const double PI = 3.14159; int choice_A; int choice_B; double total; cout << "\n\nWelcome to my shape calculator!" << endl << endl << "Please select one of the following" << endl << "1. Circle" << endl << "2. Square " << endl; cin >> choice_A; // If we run this program we can see that we are getting an invalid // output error even though we are entering valid data. Let's put in // a cout statement to see what choice_B is when it enters the switch
cout << "Debugging - choice B : " << choice_B << endl; switch(choice_B) { case 1: double radius; cout << "You have selected Circle!" << endl << endl << "Please enter the radius of your circle" << endl; cin >> radius; cout << "Please select one of the following" << endl << "1. Area" << endl << "2. Circumference" << endl; cin >> choice_B; // Here we have a switch statement incorrectly calculating // the area and circumference. Lets put some cout statements // inside each case to see which actually gets executed.
switch(choice_B) { case 1: cout << "Debugging - case 1 executed" << endl; total = PI * 2 * radius; break; case 2: cout << "Debugging - case 2 executed" << endl; total = PI * pow(radius, 2.0); break; default: cout << "invalid input. Terminating the program." << endl; break; } cout << "Result = " << total << endl; break; case 2: double length; cout << "You have selected Square!" << endl << endl << "Please enter the length of a side." << endl; cin >> length; cout << "Please select one of the following" << endl << "1. Area" << endl << "2. Perimeter" << endl; cin >> choice_B; switch(choice_B) { case 1: total = pow(length, 2.0); break; case 2: total = length * 4; break; default: cout << "invalid input. Terminating the program." << endl; break; } cout << "Result = " << total << endl; break; default: cout << "Invalid input. Terminating the program." << endl; break; } return 0; }