Switch Statements in C++

Introduction

This lab will provide students with an introduction to the fundamentals of multi-way conditional selection in the C++ programming language. The focus of this lab is on how to solve complex problems using the C++ “switch” statement. At the end of this module, students will…

  • Be able to solve simple problems using the C++“switch” statement
  • Understand the structure of the C++“switch” statement

These exercises have two different types of answers. Some questions ask for answers to specific questions; you should collect these answers in a Microsoft Word document. Other exercises ask you to write code. Let’s begin!

Part 1: Multi-Way Conditional Selection in C++

We have previously talked about multi-way conditional selection when we discussed the cascading if statement. C++ provides another multi-way selection statement called a switch statement. This allows for a more efficient selection process for those cases in which the conditional test is only a test for equality.

In this lab we will learn how to use the C++ switch statement to perform multi-way conditional selection. The switch statement has several potential advantages, including the need for less code and a greater level of execution efficiency. However, it does not provide any more functionality; switch is simply an alternative way to decide amongst a group of choices only when you are looking for an exact match.

The Switch Statement in C++

A switch statement allows for selection from multiple branches, just like a cascading if; however, the choice of which branch to take is determined by a controlling expression given in parentheses. The general form of the switch statement is as follows:

switch ( /* controlling expression */ ) 
{
   case ( /* ordinal value */ ) : 
   {
      // one or more statements to execute if the 
      // ordinal value equals the controlling expression 
      break;
   }
   case ( /* ordinal value */ ) : 
   {
      // one or more statements to execute if the 
      // ordinal value equals the controlling expression 
      break;
   }
   ...  // potentially more case clauses
   default:
   {
      // the default case; no match was found in the previous cases 
   }
}

The order of execution is as follows:

  • The value of the controlling expression is determined. The value in a controlling expression must be of an ordinal type (int, char, or bool).
  • That value is compared against each case value in turn, from the top-down.
  • As soon as an exact match is found, the block of code associated with the particular case is executed.
  • When a break statement is found, execution exits the switch and continues with the code following the end of the switchstatement.

Note that the default case is optional; it acts as an “else” case for the switch statement. The break statement is important, however, because unless it is found the code will “drop-through” and start executing the next block of code.

The switch statement is useful when you need to execute different blocks of code based on a test for equality involving an ordinal value. An ordinal value has a logical successor and predecessor; examples are int, char, or <cod

Watch and listen to the Switch Statements C++ podcast below:
switch

Part 2: User Menus and the Switch Statement

Programs requiring menus are especially good examples of when a switch is useful. Menu choices in Microsoft Windows, MAC OS X, Linux, and other Operating Systems are often represented internally as simple integers. For example, the “File -> Open” menu option could be represented by the number 1, the “File –> Save” menu option by the number 2, and so on. The ordinal nature of these options makes a switch statement a useful tool in directing the code to the proper course of action based upon which menu option was chosen by the user. The following exercise demonstrates a program which uses a menu and a switch statement to execute user commands.

Exercise 1: Suppose we wanted to reproduce a text-based computer game called “Super Star Trek”, a space simulation game created for mainframes in the 1970s. Like many text-based computer games, SST uses a series of menus to facilitate interaction with the user. When the user is presented with a list of choices, the user selects a choice by typing in an identifier for the choice (usually a simple integer). In this program, you will begin creating those menus and the code to receive the user’s choice.

Your program should include an input function designed to display the main menu and allow the user to enter their selection. A prototype for this function is as follows:

/////////////////////////////////////////////////////////////////////////////
//  
//   FUNCTION NAME: displayMainMenu
//      PARAMETERS: None
//     RETURN TYPE: int
//         PURPOSE: Displays the main menu, inputs the user’s choice (1-8),
//                  and returns the user’s choice to the calling function.
//
/////////////////////////////////////////////////////////////////////////////

int displayMainMenu();

The screen output should look like so:

                     MAIN MENU

 (1) NAV Navigate the Starship
 (2) SRS Short-Range Sensor Scan (One Quadrant)
 (3) LRS Long-Range Sensor Scan (Nine Quadrants)
 (4) PHA Phaser Control
 (5) TOR Photon Torpedo Control
 (6) SHE Shield Control
 (7) DAM Damage and State-of-Repair Report
 (8) COM Call Library Computer

Command? 

If (and only if) the user selects (8) from the main menu, display the following sub-menu:

                   
       LIBRARY COMPUTER MENU

 (0) Cumulative Galactic Record
 (1) Status Report
 (2) Photon Torpedo Course Data
 (3) Starbase Navigation Data
 (4) Direction/Distance Calculator
 (5) Quadrant Nomenclature Map

Computer Active and Awaiting Command:

Your program should have another function to display this sub-menu and receive the user’s command. A prototype for this function would be as follows:

/////////////////////////////////////////////////////////////////////////////
//  
//   FUNCTION NAME: displayLibraryMenu
//      PARAMETERS: None
//     RETURN TYPE: int
//         PURPOSE: Displays the library menu, inputs the user’s choice (1-8),
//                  and returns the user’s choice to the calling function.
//
/////////////////////////////////////////////////////////////////////////////

int displayLibraryMenu();

The algorithm for your complete program should be as follows:

  • Display the main menu and receive the user input (i.e. the command).
  • Use a switch statement to determine which command the user selected.
    • In response to a specific command, post a message to the screen (e.g. “You selected (4) PHA Phaser Control”)
    • If the user selected an invalid command, alert them to this error. Use the default case of the switch to handle this.
    • If the user selected option (8), display the library menu and receive the user input (i.e. the library command).
      • In response to a specific library command, post a message to the screen (e.g. “You selected (4) Direction/Distance Calculator”)
      • If the user selected an invalid option, alert them to this error. Use the default case of the switch to handle this.
  • End the program.

Compile and run the program, and verify that it works as it should.

Part 3: Twelve Days of Christmas

Exercise 2: Create a new C++ program called TwelveDays.cpp. The program should input the user’s choice of day (1-12) and display the corresponding gift. Use a switch statement to determine the output. Remember the following gifts are part of the “Twelve Days of Christmas”:

  • A partridge in a pear tree
  • Two turtle doves
  • Three French hens
  • Four calling birds
  • Five gold rings
  • Six geese a-laying
  • Seven swans a-swimming
  • Eight maids a-milking
  • Nine ladies dancing
  • Ten lords a-leaping’
  • Eleven pipers piping
  • Twelve drummers drumming

Test your program as well as possible, using many different inputs.