Previous Page TOC Next Page



- 10 -
Power with switch


switch


What You'll Learn About


This unit teaches you about the switch statement. The switch statement is useful for selecting from among many different actions. You've already learned about these two ways that your Visual C++ program can choose between different courses of action:

The conditional is just an efficient shortcut for implementing simple if-else logic. Both the if-else statement and the conditional operator are perfect for choosing from between two courses of action, but there are times when your program must select from more than two alternative courses. The switch statement provides you with an easy way to set up multiple-choice selection logic from within your program.

Multiple Choice with Nested ifs




You can nest if-else statements to perform multiple-choice actions.

You'll better understand the advantages of the switch statement if you first see how to implement switch logic using the if-else statement that you already know. Until now, you learned how the if-else statement selects from between two courses of action. Surprisingly, the majority of the time, your programs will choose from between only two actions at a time, so if-else (or the simplified conditional operator in many cases) is a statement you'll use a lot. However, when your program must select from among many possible courses of action, you have to stack if-else logic, nesting the statements, to achieve a multiple-choice selection.

Suppose that a program you write for a credit-reporting agency needs to charge a different customer-loan percentage based on the current customer's credit rating of A (good) or B (fair). Only two courses of action are necessary, so this simple if-else statement works fine:


if (rating == 'A')

  { loanRate = .11; }   // Good rating

else

  { loanRate = .13; }   // Fair rating

// Rest of loan program logic would follow

Using pseudocode, here is what the preceding if-else states:

If the customer's rating is A,
the customer's loan rate should be 11%.
Otherwise,
the customer's loan rate should be 13%.



It's a good idea to use pseudocode to explain program logic. The specific syntax of the programming language doesn't get in the way. Seeing pseudocode with the if-else statement that you already know will make it that much easier for you to understand later pseudocode that explains the switch statement.

There are two (and only two) options in this logic. Either the customer's rating is A, or the rating is not A, which means that the rating has to be B. No explicit test for the B has to be made, because there are only two options. If the test for A fails, the rating has to be B.

Let's introduce a third option, a rating of C for a poor credit history. The program must now choose from among three options: A, B, or C. A simple if-else won't work. The third option requires a nested if like this one:


if (rating == 'A')

  { loanRate = .11; }   // Good rating

else

  if (rating == 'B')      // Must test explicitly

    { loanRate = .13; }   // for the fair rating

  else

    { loanRate = .15; }   // Poor rating

// Rest of loan program logic would follow

As soon as you add a nested if, the logic gets more convoluted. However, one or even two levels of nesting don't complicate the logic too much for understanding. Here is the pseudocode for this nested if:

If the customer's rating is A,
the customer's loan rate should be 11%.
Otherwise,
if the customer's rating is B,
the customer's loan rate should be 13%.
Otherwise,
the customer's loan rate should be 15%.

Do you see why no explicit test was needed to see whether the rating was C? It was assumed that there were only three choices—A, B, or C. (Perhaps input validation performed earlier in the program ensured that only these three valid values were entered.) If the rating wasn't A, and if the rating wasn't B, the rating had to be C, and the appropriate loan rate was computed accordingly.

The problem with nested if-else logic is that too many levels of nesting introduce difficult-to-follow logic. Although one or even two nested if statements aren't impossible to follow, there has to be a better way to represent multiple-choice logic. There is a better way, as you'll see in the next section.

To see how such embedded ifs can really confuse, what if there are six different credit ratings to deal with? Here is a way to represent such a large number of options:


if (rating == 'A')

  { loanRate = .11; }

else 

  if (rating == 'B')

    { loanRate = .13; }

  else 

    if (rating == 'C')

      { loanRate = .15; }

    else 

      if (rating == 'D')

        { loanRate = .17; }

      else 

        if (rating == 'E')

          { loanRate = .19; }

        else 

          {loanRate = .21; }

// Rest of loan program logic would follow

Some credit agencies have many more kinds of credit ratings than the six shown here, so the problem of selecting from multiple-choice logic, with its many possible outcomes, gets to be a real burden for programmers. Some programmers opt to code only if statements without embedded if-else logic, like this:


if (rating == 'A')

  { loanRate = .11; }

if (rating == 'B')

  { loanRate = .13; }

if (rating == 'C')

  { loanRate = .15; }

if (rating == 'D')

  { loanRate = .17; }

if (rating == 'E')

  { loanRate = .19; }

if (rating == 'F')

  { loanRate = .21; }

// Rest of loan program logic would follow

Such simple sequential if logic might be slightly easier to follow than the previous embedded if-else logic, but the code isn't as efficient. You should agree that readability is more important than efficiency, but this code is extremely less efficient than the nested ifs, and it only gets worse as you add more if options. If the credit rating is A, each of the additional ifs is still checked. With nested ifs, however, if the first if is true, none of the other ifs are checked.

Programmers have designed special charts that help demonstrate nested logic, such as the one shown in Figure 10.1. However, nothing seems to be as helpful as simply introducing a new statement into the language, such as the switch statement, whose very syntax lends itself well to a program's multiple-choice selection.

Figure 10.1. A diagram that helps show embedded if logic.

Listing 10.1 uses an embedded if-else to perform multiple-choice selection. The user's favorite local TV channel is asked for, and an appropriate message prints.



Embedded if-else statements let you select from among several alternatives, but embedded ifs are not very easy to maintain. As soon as you understand how embedded if-else statements work, you'll be ready to learn about the switch statement, which removes much of the multiple-choice selection burden from your programming shoulders.

Input Listing 10.1. Using embedded if-else logic to select an appropriate message.

  1:// Filename: IFELSETV.CPP

  2:// This program uses embedded if-else statements to print

  3:// a message for the user. The printed message corresponds

  4:// to the user's favorite television channel.

  5:#include <iostream.h>

  6:void main()

  7:{

  8:  int channel;

  9:

 10:  cout << "In this town, there are five non-cable television ";

 11:  cout << "channels." << endl;

 12:  cout << "What is your favorite (2, 4, 6, 8, or 11)? ";

 13:  cin >> channel;

 14:  cout << endl << endl;   // Output two blank lines

 15:

 16:  // Use an embedded if to print appropriate messages

 17:  if (channel == 2)

 18:    { cout << "Channel 2 got top ratings last week!"; }

 19:  else

 20:    if (channel == 4)

 21:     { cout << "Channel 4 shows the most news!"; }

 22:       else

 23:         if (channel == 6)

 24:           { cout << "Channel 6 shows old movies!"; }

 25:         else

 26:           if (channel == 8)

 27:             { cout << "Channel 8 covers many local events!"; }

 28:           else

 29:             if (channel == 11)

 30:               { cout << "Channel 11 is public broadcasting!"; }

 31:             else   // The logic gets here only if the

 32:                    // user entered an incorrect channel

 33:               { cout << "Channel " << channel

 34:                      << " does not exist; it must be cable."; }

 35:

 36:  cout << endl << endl << "Happy watching!";

 37:  return;

 38:}

OUTPUT



Three different runs are shown to demonstrate the program's multiple-choice aspect.


In this town, there are five non-cable television channels.

What is your favorite (2, 4, 6, 8, or 11)? 6

Channel 6 shows old movies!

Happy watching!

In this town, there are five non-cable television channels.

What is your favorite (2, 4, 6, 8, or 11)? 2

Channel 2 got top ratings last week!

Happy watching!

In this town, there are five non-cable television channels.

What is your favorite (2, 4, 6, 8, or 11)? 3

Channel 3 does not exist; it must be cable.

Happy watching!

ANALYSIS

If you understand if, just multiply that understanding by five and you'll understand this program! Seriously, embedded if statements do multiply the difficulty of following a program's logic.

One argument within the Visual C++ programming community concerns how programmers should indent embedded logic such as that in Listing 10.1. Some prefer to embed as shown here, while others want to put braces around each embedded if (which results in a series of several closing braces all grouped toward the end of the program). Still others want to align all the if and else bodies evenly so that the code doesn't get pushed too far to the right in the last few embedded statements.

If you prefer to embed if-else logic, and if you don't have a problem understanding such code (not everyone feels that nested ifs are difficult), there is certainly nothing wrong with using it as done in Listing 10.1. However, after you learn about the switch statement in the next section, you'll probably prefer to use switch for much of your multiple-choice processing.



Despite the advantages of switch, nothing beats if-else for straightforward logic when only two choices must be made. Also, if the code is simple, use the conditional operator for efficiency. The switch statement can be overkill for simple choices. I'm not recommending that you cease to use if-else logic.


Making the switch




Use the switch statement to code multiple-choice logic. You will improve your program's clarity and make future maintenance much easier.

Unlike embedded if-else logic, the switch statement doesn't need a lot of fancy indentation that causes code to move closer to the right margin as the statement gets longer. Here is the format of switch. Even though the format looks a little intimidating, you'll see that switch is one of the easiest statements that Visual C++ offers.


switch (expression)

  { 

    case (expression) : 

      {   // Block of one or

          // more Visual C++ statements

      }

    case (expression) : 

      {   // Block of one or

          // more Visual C++ statements

      }

    // If there are more case

    // statements, put them here

    case (expression) : 

      {   // Block of one or

          // more Visual C++ statements

      }

    default :           

      {   // Block of one or

          // more Visual C++ statements

      }

  }

switch might span more lines than shown in the format, depending on how many choices must be made. The expression following switch must evaluate to an integer or character-data type. Here is how switch works (using pseudocode again):

If the value of the switch expression matches that of the first case
expression, execute the first block of code.
If the value of the switch expression matches that of the second case
expression, execute the second block of code.
Continue looking for a match throughout the case expressions that
compare to the switch's expression and execute the appropriate code.
If none of the case expressions matches the switch expression,
execute the default block of code.

Did the pseudocode help? If not, looking at the following actual switch might:


cout << "What is the customer's credit rating (A, B, C, or D)? ";

cin >> rating;

switch (rating)   // The switch value must be an int or char

  { 

    case ('A') : 

      { 

        loanRate = .11;

        break;

      }

    case ('B') : 

      { 

        loanRate = .13;

        break;

      }

    case ('C') : 

      { 

        loanRate = .15;

        break;

      }

    case ('D') : 

      { 

        loanRate = .17;

        break;

      }

    default :    

      { 

         cout << "You didn't enter a valid rating." << endl;

         break;

      }

  }   // Don't forget this required closing brace!

You should be able to read and understand this switch statement with little trouble. Ignoring the breaks for now, the user's credit rating determines exactly which block of code Visual C++ executes. If the rating is A, the first case block (the one that sets the loan rate to 11 percent) executes. If the rating is B, the second case block (the one that sets the loan rate to 13 percent) executes, and so on.

The default portion of switch tells Visual C++ what to do if none of the other case statements matches the switch expression's value. Therefore, if the user didn't enter an A, B, C, or D, the default block of code executes, which is nothing more than an error message for the user.

switch doesn't perform automatic uppercase and lowercase conversions. Therefore, if the user enters a lowercase a, b, c, or d, switch won't match any of the case expressions due to their uppercase forms.



Before entering a switch statement, your program should convert the switch expression to uppercase if you're using a character value for the switch expression.

The format and indentation that you see in this switch statement is fairly common. Be sure to remember the closing brace, because it's easy to forget. (Of course, the Visual C++ compiler won't let you forget it!)

Listing 10.2 contains the television channel program that you saw in Listing 10.1. Instead of embedded if statements, switch makes the logic cleaner and easier to follow.



The next section explains why so many breaks appear in switch statements.



The switch statement gives you a maintainable statement that selects from one of many multiple-choice actions. A data value—either an integer or a character—decides which action executes.

Input Listing 10.2. The television channel program using switch instead of ifs.

1:// Filename: SWITCHTV.CPP

  2:// This program uses a switch statement to print a message

  3:// to the user. The printed message corresponds to the

  4:// user's favorite television channel.

  5:#include <iostream.h>

  6:

  7:void main()

  8:{

  9:  int channel;

 10:

 11:  cout << "In this town, there are five non-cable television ";

 12:  cout << "channels." << endl;

 13:  cout << "What is your favorite (2, 4, 6, 8, or 11)? ";

 14:  cin >> channel;

 15:  cout << endl << endl;   // Output two blank lines

 16:

 17:  // Use a switch to print appropriate messages

 18:  switch (channel)

 19:    { 

 20:      case (2) : 

 21:        { 

 22:          cout << "Channel 2 got top ratings last week!";

 23:          break; 

 24:        }

 25:      case (4) : 

 26:        { 

 27:          cout << "Channel 4 shows the most news!";

 28:          break; 

 29:        }

 30:      case (6) : 

 31:        { 

 32:          cout << "Channel 6 shows old movies!";

 33:          break;

 34:        }

 35:      case (8) : 

 36:        { 

 37:          cout << "Channel 8 covers many local events!";

 38:          break; 

 39:        }

 40:      case (11):

 41:        { 

 42:          cout << "Channel 11 is public broadcasting!";

 43:          break; 

 44:        }

 45:      default  :  // Logic gets here only if

 46:                  // user entered an incorrect channel

 47:        { 

 48:          cout << "Channel " << channel

 49:               << " does not exist, it must be cable."; 

 50:        }

 51:    }

 52:

 53:  cout << endl << "Happy watching!";

 54:  return;

 55:}

OUTPUT



Notice that the output for this program is identical to that of Listing 10.1, despite the fact that a switch statement replaces the embedded if-elses.


In this town, there are five non-cable television channels.

What is your favorite (2, 4, 6, 8, or 11)? 6

Channel 6 shows old movies!

Happy watching!

In this town, there are five non-cable television channels.

What is your favorite (2, 4, 6, 8, or 11)? 2

Channel 2 got top ratings last week!

Happy watching!

In this town, there are five non-cable television channels.

What is your favorite (2, 4, 6, 8, or 11)? 3

Channel 3 does not exist, it must be cable.

Happy watching!

ANALYSIS

The user's value is either 2, 4, 6, 8, or 11, and only one of the switch statement's blocks executes when one of those values matches a case expression's. If the user doesn't enter a correct value (one that matches the case statement's), the default section takes over and prints an appropriate message. default is a lot like a catch-all if-else statement. It handles any switch value not matched by a case statement.

Both the switch and the case expressions can contain variables and operators if you need to calculate a value, as long as the expression that you use results in an integer or character value.



A default section isn't mandatory. If previous input validation ensures that the user's value will match one of the case expressions, no default is needed.


break Up That switch




The switch statement's breaks ensure that each case block doesn't fall through and execute subsequent case blocks.

Although switch statements don't have to contain break statements, they almost always do. break ensures that each case doesn't fall through to the next case blocks. Here is a switch that contains no break statements:


switch (value)

  { 

    case (1) : { cout << "You entered a 1" << endl; }

    case (2) : { cout << "You entered a 2" << endl; }

    case (3) : { cout << "You entered a 3" << endl; }

    case (4) : { cout << "You entered a 4" << endl; }

    default  : { cout << "I don't know what you entered!" << endl; }

  }


Notice the braces around each of the case blocks. Because each block has only a single statement, the braces aren't necessary. However, as with the if, the while loops, and the for loop, braces are always recommended.

Figure 10.2 shows the execution path if the user's value is 1. Notice that every cout executes!

Figure 10.2. Without break, execution falls through all couts.

Here is the output when Visual C++ executes this switch without breaks (assuming that value is equal to 1):


You entered a 1

You entered a 2

You entered a 3

You entered a 4

I don't know what you entered!

There's a big potential problem here! The switch statement will always fall through each case statement unless a break statement terminates each of the case blocks of code. If value had a 3, this would be the output:


You entered a 3

You entered a 4

I don't know what you entered!

The first two case statements don't execute, but as soon as Visual C++ finds a case to match the 3, Visual C++ executes all remaining case blocks of code.

Most of the time, your logic will require that you insert break statements to the end of each case block of code as done here:


switch (value)

{ case (1) : 

    { cout << "You entered a 1"  << endl;

      break; 

    }

  case (2) :

    { cout << "You entered a 2" << endl;

      break; 

    }

  case (3) : 

    { cout << "You entered a 3" << endl;

      break;

    }

   case (4) : 

    { cout << "You entered a 4" << endl;

      break; 

    }

   default  : 

     { cout << "I don't know what you entered!" << endl;

       break; 

     }

}

Figure 10.3 shows the action of this switch if value is equal to 1. The case blocks are now truly mutually exclusive; one and only one case block executes for each execution of the switch.

Figure 10.3. With break, execution terminates after one cout.

If the user enters a 1, here is the output:


You entered a 1

If the user enters a 3, here is the output:


You entered a 3


Try to put the most often selected case at the top of the switch statement. The faster case matches the switch expression, the less searching Visual C++ has to do to find the right match, and the more efficient your code will be.



If you happen to put more than one case inside a switch with the same expression, Visual C++ matches only the first one.

The fall-through execution of the case code is actually to your advantage sometimes. For example, there could be a time when your program must calculate five values, or only four, or only three, or only two, or only one (such as when computing a country's, or a region's, or a state's, or a city's, or a person's sales values), depending on the data. You can arrange five case statements without breaks to execute five calculations if the switch expression matches the first case, or four calculations if the switch expression matches the second case, and so on, creating a cascading flow of calculations.


One of the things that a switch can't do is choose from a range of values. For example, if you must execute the same code based on a 1, 2, or 3, and the same code for a 4, 5, or 6, you have to resort to the following coding technique:

switch (value)

  { case (1) :

    case (2) :

    case (3) : {   // The case code for 1, 2, or 3

                 break;

               }

    case (4) :

    case (5) :

    case (6) : {   // The case code for 4, 5, or 6

                 break;

               }

    default :  {   // The code for other values

                 break;

               }

  }

You also can control range-checking by using a menu, as discussed in the Homework section at the end of this unit.


Why Is That Final break There?

The Pascal programming language contains a CASE statement that works a lot like Visual C++'s switch. Pascal, however, guarantees that one and only one of the selected values will execute. If one of the options matches the CASE statement, Pascal executes only that code and terminates the statement without the need for break statements.

Visual C++ requires a little more work on your part if you want only a single case block of code to execute. You must insert break statements at the end of every case code if you don't want the execution to fall through the other case blocks. However, this extra effort gives you the ability to write a switch statement that terminates after a single case or one that cascades through the other case statements, which Pascal doesn't allow.

You might wonder why the default option needs a break. After all, when default finishes, won't Visual C++ move on to the next statement? There are no more case statements for the execution to fall through to. A break isn't required at the end of the default block of code, but try to get in the habit of including it. If you later rearrange the case blocks for efficiency, and one of the blocks that you rearrange is the default block, the break will already be there.


Listing 10.3 contains a program that prints the country's sales value, a region's sales value, a state's sales value, or the local sales value, depending on the user's request.



The placement of break statements or the lack of break statements determines whether or not Visual C++'s case code falls through the other case blocks.

Input Listing 10.3. Prints five, four, three, two, or one messages, depending on the user's request.

  1:// Filename: NOBREAKS.CPP

  2:// Not using break statements inside a switch lets

  3:// you cascade through the subsequent case blocks

  4:#include <iostream.h>

  5:

  6:void main()

  7:{

  8:  char request;

  9:

 10:  cout << "Sales Reporting System"  << endl << endl;

 11:

 12:  cout << "Do you want the Country, Region, State, or Local report";

 13:  cout << " (C, R, S, or L)? ";

 14:  cin >> request;

 15:  cout << endl;

 16:

 17:  //

 18:  // Convert to uppercase - letters are contiguous

 19:  //

 20:  if (request >= 'a' || request <= 'z')

 21:    request += ('A' - 'a');

 22:  

 23:  switch (request)

 24:    { 

 25:      case ('C') : 

 26:        { 

 27:          cout << "Country's sales: $343,454.32" << endl; 

 28:        }

 29:      case ('R') : 

 30:        { 

 31:          cout << "Region's sales: $64,682.01" << endl; 

 32:        }

 33:      case ('S') : 

 34:        { 

 35:          cout << "State's sales: $12,309.82" << endl; 

 36:        }

 37:      case ('L') : 

 38:        { 

 39:          cout << "Local's sales: $3,654.58" << endl;

 40:          break; 

 41:        }

 42:      default    : 

 43:        { 

 44:          cout << "You did not enter C, R, S, or L"  << endl;

 45:          break; 

 46:        }

 47:    }

 48:  return;

 49:}

OUTPUT



Three different outputs are shown so that you can see how switch handles the different requests.


Sales Reporting System

Do you want the Country, Region, State, or Local report (C, R, S, or L)? c

The country's sales are $343,454.32

The region's sales are $64,682.01

The state's sales are $12,309.82

The local sales are $3,654.58

Sales Reporting System

Do you want the Country, Region, State, or Local report (C, R, S, or L)? L

The local sales are $3,654.58

Sales Reporting System

Do you want the Country, Region, State, or Local report (C, R, S, or L)? x

You did not enter C, R, S, or L

ANALYSIS

This program contains four case blocks, as well as a default block that handles any unmatched expressions. All four sales figures are to be printed if the country's sales are requested, so no break appears in the first four case blocks to allow the execution to fall through.

The code in lines 20 and 21 converts the lowercase entry into uppercase. You might not know the numeric difference between 'a' and 'A', but you know that all the uppercase letters and the lowercase letters come together in the ASCII table. This code will work whatever the actual values of 'a' and 'A' are.

There is a break on line 40 so that a previous case execution doesn't fall through to the default's code. Without that break, entering L (for local) would produce this output:


Sales Reporting System

Do you want the Country, Region, State, or Local report (C, R, S, or L)? L

The local sales are $3,654.58

You did not enter C, R, S, or L

Obviously, the break before the default block is needed to keep the error from appearing when the user enters a correct value.

Using switch for Menus




Menus are common programming methods that give the user several options from which to choose.

Whenever you sit down in a new restaurant, what must you have before you order food? (From the title of this section, you already know what's coming!) You need a menu. You can't be expected to know in advance what food every restaurant will have (MacDonalds excepted!).

When your users sit down in front of your program, you can't always expect them to know what's possible either. You need to give them a choice of options that they can order. Such options usually are found on menus.

Obviously, the concept of a menu is nothing new to you, a top-notch Visual C++ programmer. You've been using the pull-down menus from Visual C++'s workbench throughout this book. When writing programs, you'll add menus to your programs so that your user can have access to a list of choices, just as you do in the workbench.

I'm not trying to fool you here! The menus that you write using this book won't be the fancy pull-down types that Visual C++ contains. Such menus are extremely difficult to code, and you have to learn to walk before you can run. The menus you write will do little more than display a list of choices such as these:


Here are your choices:

1. Print an employee report

2. Enter sales figures

3. Compute payroll

4. Exit the program

What do you want to do?


Despite the fact that this menu isn't of the fancy pull-down kind, its simplicity is its power. This kind of list menu is easy to code and easy for the user to use.

After you grab the user's input, your program must figure out what the user entered and execute the appropriate routine. Hey, that's a great job for the switch statement! One of the most common uses for switch is for menu processing. The multiple-choice selection that menus need matches the multiple-choice selection that the switch statement provides.

Listing 10.4 contains a menu that calculates different kinds of mathematical results based on the user's menu selection.



The switch statement is perfect for writing menu selection code.

Input Listing 10.4. Using switch to perform the user's calculation.

1:// Filename: MATHMENU.CPP

  2:// Uses a switch statement to perform

  3:// menu actions for the user

  4:#include <iostream.h>

  5:

  6:void main()

  7:{

  8:  const int PI = 3.14159;

  9:  int menu;       // Will hold menu result

 10:  int num;        // Will hold user's numeric value

 11:  float result;   // Will hold computed answer

 12:

 13:  cout << "Math Calculations" << endl << endl;

 14:  cout << "Please enter a number from 1 to 30: ";

 15:  cin >> num;

 16:  if ( (num < 1) && (num > 30));   

 17:    {

 18:      return;  // Exit if bad input

 19:    }

 20:    

 21:  cout << "Here are your choices:" << endl << endl;

 22:  cout << "\t1. Calculate the absolute value" << endl;

 23:  cout << "\t2. Calculate the square" << endl;

 24:  cout << "\t3. Calculate the cube" << endl;

 25:  cout << "\t4. Calculate a circle's area" << endl;

 26:  cout << "\t   using your radius" << endl;

 27:  cout << endl << "What do you want to do? ";

 28:  cin >> menu;

 29:

 30:  switch (menu)

 31:    { 

 32:      case (1) : 

 33:        { 

 34:          result = ((num < 0)? -num : num);

 35:          break;

 36:        }

 37:      case (2) : 

 38:        { 

 39:          result = num * num;

 40:          break;

 41:        }

 42:      case (3) : 

 43:        { 

 44:          result = num * num * num;

 45:          break;

 46:        }

 47:      case (4) : 

 48:        { 

 49:          result = PI * (num * num);

 50:          break;

 51:        }

 52:      default  : 

 53:        { 

 54:          cout << "You did not enter 1, 2, 3, or 4" << endl;

 55:          return;   // Terminate the whole program

 56:                    // No need for a break

 57:        }

 58:    }

 59:

 60:  cout << endl << "Here is your computed value: " 

 61:       << result << endl;

 62:  return;

 63:}

OUTPUT



Two outputs appear.


Math Calculations

Please enter a number from 1 to 30: 10

Here are your choices:

1. Calculate the absolute value

2. Calculate the square

3. Calculate the cube

4. Calculate a circle's area

   using your radius

What do you want to do? 2

Here is your computed value: 100.00

Math Calculations

Please enter a number from 1 to 30: 6

Here are your choices:

1. Calculate the absolute value

2. Calculate the square

3. Calculate the cube

4. Calculate a circle's area

   using your radius

What do you want to do? 6

You did not enter 1, 2, 3, or 4

ANALYSIS

One of four math calculations is performed, based on the user's request. The menu gives the user a nice display of every option available.

The program first asks for a number in lines 16 through 20. The if ensures that the user enters a value from 1 to 30. After the program accepts the user's number, the user sees the menu printed on lines 21 through 27. The user is to enter a value from 1 to 4. No fancy error checking is done. If the user enters a value that isn't in the range of 1 to 4, the program prints an error message (line 54) and exits via the return on line 55.



Without the return at the end of the default option, execution would fall through to print the message in line 60. Line 60's message should be printed only if the user entered a menu option from 1 to 4.


Homework



General Knowledge


  1. What is a disadvantage of nested if-else statements?

  2. How can using a switch statement improve the readability of nested if-else statements?

  3. Are braces required around every case block? Why or why not?

  4. What kind of data type must the switch expression evaluate to?

  5. What happens if none of the case expressions matches the switch expression?

  6. Why would a programmer possibly want to reorder the case statements in a program?

  7. What happens if you don't put break statements at the end of switch blocks?

  8. What happens if more than one case block contains the same expression?

  9. What do you insert in a case statement to capture an expression that doesn't match any of the other case expressions?

  10. Which case block executes if you don't include a default block and none of the case expressions matches the value of the switch expression?

  11. Why is it a good idea to put a break at the end of a default block of code?

  12. True or false: The switch statement is one of the longest Visual C++ statements and therefore is the most complicated.

  13. True or false: The default block is optional.

  14. True or false: Forgetting to insert break statements at the end of switch blocks will introduce bugs into your program.

  15. True or false: The switch statement requires the STDLIB.H header file.

  16. True or false: switch statements improve the readability of nested for loops.

    What's the Output?


  17. What's the output of the following switch statement?

    
    switch ('A') :
    
      { case ('A') : cout << "Apples" << endl;
    
        case ('B') : cout << "Bananas" << endl;
    
        case ('C') : cout << "Carrots" << endl;
    
        default    : cout << "Onions" << endl;
    
      }

    Find the Bug


  18. Although the following switch doesn't contain a syntax error, each line of code in each case is missing a couple of special characters that might come in handy later. What could you add to aid in the future maintenance of this switch?

    
    switch (ans)
    
      { case (1) : cout << "The answer is 1" << endl;
    
        default : cout << "The switch statement is not finished." << endl);
    
      }

  19. Rudy can't seem to get his switch statement to work. He's writing a program to control departmental duty reports, but too many departments print at once. Can you help Rudy by rewriting this switch so that each case block executes independently of the others?

    
    switch (ans)
    
      { case (2) : { cout << "Your department isn't on duty today."; }
    
        case (5) : { cout << "Your department begins duty at 4:00"; }
    
        case (9) : { cout << "Your department works overtime Monday."; }
    
        default :  { cout << "Your department is in conference now."; }
    
      }
    
    cout << "" << endl;

  20. What's wrong with the following switch statement?

    
    switch (choice)
    
      case (1) : { ans = 34 * sales;
    
                   break; }
    
      case (2) : { ans = 56 * sales;
    
                   break; }
    
      case (3) : { ans = 78 * sales;
    
                   break; }
    
      default  : { ans = sales;
    
                   break; }

    Write Code That. . .


  21. Ask the user for a number from 1 to 5. Using a switch statement, print the name of the number (for example, print two if the user enters 2). Include an error-checking loop to ensure that the user enters a number in the range of 1 to 5.

  22. Wilma coded the following nested if-else statement, but she's having a hard time understanding it, even though it seems to be working correctly. Rewrite the statement as a switch to help Wilma's future program maintenance.

    
    if (num == 1)
    
      { cout << "France" << endl; }
    
    else if (num == 2)
    
      { cout << "Italy" << endl; }
    
      else if (num == 3)
    
        { cout << "England" << endl; }
    
        else { cout << "Greece" << endl; }

  23. Although a switch statement can't deal directly with ranges of values, you can display a menu of ranges, with numbers 1 through the total number of menu options to the left of each range, and base a switch statement on the menu's ranges. Write a program that computes a sales bonus of $0 if the user sold fewer than 100 products, a sales bonus of $50 if the user sold between 101 and 200 products, and a sales bonus of $100 if the user sold more than 200 products.

    Extra Credit


  24. Write a program that calculates tolls for an interstate toll booth. Ask whether the driver is in a car or a truck. Calculate a charge of $3.00 if the driver got on the toll road within the last 75 miles, $3.50 if the driver got on the toll road within the last 125 miles, and $4.00 if the driver got on the toll road more than 125 miles ago. If the vehicle is a truck, add an extra $1.00 for the added weight. (Hint: Use one switch and one if statement.)

Previous Page Page Top TOC Next Page