Chapter 10 – Switch Statement

The switch statement can used as an alternative to if...else statements when the value of a single variable needs to provide multiple choices.  The following code demonstrates the switch statement.

switch(Day)
{
   case 1:
      cout << "Sunday";
      break;
   case 2:
      cout << "Monday";
      break;
   case 3:
      cout << "Tuesday";
      break;
   case 4:
      cout << "Wednesday";
      break;
   case 5:
      cout << "Thursday";
      break;
   case 6:
      cout << "Friday";
      break;
   case 7:
      cout << "Saturday";
      break;
   default:
      cout << "Invalid Day";

As can be seen in the previous switch statement, the optional default statement can be included to provide a branch if none of the other cases execute.  In a switch statement, it is not necessary to use braces for each case, even if you have multiple lines of code to execute.  It is important to remember to put a break after each case, otherwise all remaining cases will execute.  The next program demonstrates another switch statement.

Program   10.1 – Switch Statement

#include <iostream>
using namespace std;

main()
{
  short int Year;
  cout << "Enter a year to see any famous events: ";
  cin >> Year;
  switch(Year)
  {
    case 1492:
      cout << "Columbus sailed the ocean blue.\n";
      break;
    case 1776:
      cout << "The United States comes into being.\n";
      break;
    case 1963:
      cout << "Kennedy assassinated.\n";
      break;
    case 1969:
      cout << "First person lands on the moon.\n";
      break;
    case 2002:
      cout << "Learning C++ for Geniuses-- is written.\n";
      break;
      default:
      cout << "No famous events this year.\n";
  }
}

Output
Enter a year to see any famous events: 1969
First person lands on the moon.