Switch Statements


if statements and if-else statements are great if you have one or two choices. But what happens when you have several choices? You can still use a series of if-else statements, but that quickly becomes cumbersome. Fortunately, there is another choice—the switch statement. A switch statement is literally saying, “switch the path you take through the code based on the value of some variable.” A switch can only be done on a single character or on an integer value. You can also think of a switch statement as a complex version of the if statement. It’s a way of using if statements when there are multiple possible choices. Switch statements, like if statements, exist in most programming languages and the structure is the same. The structure for a switch statement is shown in Figure 5.1C.

click to expand
Figure 5.1C: Structure of a switch statement.

The implementation of the switch statement in C++ is relatively straightforward. Let’s take a look at an example in the following code segment.

int choice switch (choice) { case 1: cout << "You chose 1 \n"; break; case 2: cout << "You chose 2 \n"; break;   case 3: cout << "You chose 3 \n"; break;   default: cout << "You made an invalid choice \n"; break; }

If you examine this code, you will notice several things. First, you will notice the brackets. The brackets start right after the switch statement and end after the last statement in the switch. A switch statement is a code block, just like an entire function or an if statement. And remember that all code blocks are bounded by brackets. You should also notice that each case has a number then a colon. What the code is literally saying is “if it is the case that the integer choice is equal to one, then execute this code.” At the end of each case, there is a break statement. This is very important. Without it, the code will continue to execute and will run the next case statement as well. Finally, we have a default statement. If the variable we are switching on does not match any of our cases, then the default will occur.

It is sometimes helpful to think of a switch statement like a switch on a railroad track. You will switch the direction you travel through the code, based on the value of the variable you have selected to base your switch on. Like if statements, the switch is common to most programming languages, just its implementation is different. Lets take a look at a program that uses a switch case statement to create a menu the user can select from. This program will also incorporate other concepts that we have already covered in this book.

Example 5.3a

Step 1: Open your favorite text editor and type in the following code, and save it as 05-03a.h.

void menu(); float circle_area(float); float triangle_area(float, float); float rectangle_area (float, float);

Step 2: Open your favorite text editor and type in the following code.

#include "05-03.h" #include <iostream> using namespace std; int main() {   // call the menu to cause it to display initially   menu();   return 0; }// end of main function void menu() {  int menuchoice;  float radius, height, width, base, answer;  char somechar; // This first section simply displays the users choices  // then  // prompts the user to make a selection. cout << "1. Area of a circle \n"; cout << "2. Area of a triangle \n"; cout << "3. Area of a rectangle \n"; cout << "4. Exit \n"; cout << " \n  Please enter the number of your selection   \n"; cin >> menuchoice;  // whatever choice the user makes  // will be stored in the variable  // menuchoice  // This next section uses a switch case statement to   //  determine the course of action  // based on what the user chose. switch (menuchoice) { case 1: // area of circle  cout << "Please enter the radius of the  circle \n";  cin >> radius;  answer = circle_area(radius);  break; case 2: //area of triangle  cout << "Please enter the base of the     triangle \n";  cin >> base;  cout << "Please enter the height of the     triangle \n";  cin >> height;  answer = triangle_area(base, height);  break; case 3: // area of rectangle  cout << "Please enter the height of the    rectangle \n";  cin >> height; cout << "Please enter the width of the    rectangle \n";  cin >> width;  answer = rectangle_area(height, width);  break;        case 4: // exit return;    default:     cout << "Sorry, that was not a valid entry.      Please try again \n";    menu(); // it redisplays the menu   }// end of switch   cout << "The answer is " << answer << "\n";   cout << " Press the enter/return key to continue  \n";   cin >> somechar ; // it does not matter what they  // press   menu () ; // redisplay the  menu. }// end of menu function float circle_area(float radius) {  float area;  area = 3.14 * ( radius * radius);  return area; } float triangle_area(float height, float base) {   float area;   area = .5 * (base * height);   return area; }    float rectangle_area(float height, float width) {   float area;   area = height * width;   return area;    }

Step 3: Compile the code.

Step 4: If all goes well, you should see something like what is displayed in Figure 5.2A.

click to expand
Figure 5.2A: Switch statements.

Hint!

You should note that when we include a header file that we create, it is put inside quotation marks, not inside brackets. Header files that are not found in the include directory that installed with your compiler must be put inside quotation marks, and must include the .h extension. The include directory is the directory/folder where the compiler looks for various header files such as iostream, fstream, and cmath.

This is the longest program you have seen yet in this book but don’t be concerned. We are going to review this program, piece by piece, and see what is happening. Hopefully your reading thus far, combined with the numerous comments in the previous code, have given you at least some understanding of what is happening. To begin with, we put the menu in a separate function. The reason for this is so that you could call it repeatedly. You will note that after the answer is returned and displayed on the screen, that we call the menu function again. This means that each time an operation is done, the menu will redisplay and the user can then choose to either perform another operation, or to exit. You should also notice that the function prototyping is all done in a header file.

The actual menu function is the largest and most complex function in this program. The first part of it simply uses a series of cout statements to display choices on the screen, then it prompts the user to make a selection. That selection is stored in a variable named menuchoice. (This name indicates what the variable does.) Then we have a switch case statement that selects a course of action based on the value in that variable. Depending on what choice the user made, the user would be prompted for specific input, the area of the shape they chose would be computed, and then the answer would be returned. Because returning the answer will be the same for all the various choices, that is left until after the switch case. Also notice that after the answer is displayed, the menu is redisplayed. This allows the user to make multiple selections.

Watchout!

Remember that you must have break statements after each case. Without them, the next case statement will also be executed.

As you can see, the switch statement is more versatile than the if statement. Anytime you have more than two or three choices you should definitely consider using the switch statement rather than an if statement. Also note you have a default option with switch statements that you do not have with if statements.

Example 5.3b

Step 1: Type the following code into your favorite text editor and save it as 5.3b.cpp.

#include <iostream> using namespace std; void menu(); int main() {  menu();  return 0; }// end of main void menu() { int choice;      float area, base, height, radius;      cout << "1. Area of triangle \n";      cout << "2. Area of circle \n";      cout << "3. Exit \n";      cin >> choice;      switch(choice)      {      case 1: cout << "1. metric \n";      cout << "2. english \n";      cin >> choice;      cout << "Enter base \n";      cin >> base;      cout << "Enter Height \n";      cin >> height;      area = .5f * (base * height);      switch(choice)      {      case 1:     cout << "The area is "<<area << " square     meters \n";      break;      case 2:    cout << "The area is "<< area <<" square feet    \n";      break;      default:      cout << "Invalid Choice \n";      }// end of inner switch      break;      case 2:      cout << "1. Metric \n";      cout << "2. English \n";      cin >> choice;      cout << "Enter the radius \n";      cin >> radius;      area = 3.14f * (radius * radius);      switch(choice)      {      case 1:     cout << "The area is "<<area << " square    meters \n";      break;      case 2:    cout << "The area is "<< area <<" square feet   \n";      break;      default:      cout << "Invalid Choice \n";      }// end of inner switch            break;      case 3: return;      break;      default:      cout << "Invalid selection \n";      }      menu(); }

Step 2: Compile and execute this code. You should see something similar to what is shown in Figure 5.2B.

click to expand
Figure 5.2B: Nested switch statements.

You can see how nested switch statements can be used to provide another layer of possible branching. Nested if statements, switch statements, and loops are very common, you will probably encounter them often.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net