The switch Statement

Tom Kelliher, CS17

Apr. 17, 1996

Multiway Selection and the switch Statement

We already have multiway selection with the if:

char letterGrade(int numberGrade)
{
   if (numberGrade < 60)
      return 'F';
   else if (numberGrade < 70)
      return 'D';
   else if (numberGrade < 80)
      return 'C';
   else if (numberGrade < 90)
      return 'B';
   else
      return 'A';
}

switch statement allows you to ``jump'' to a label in a following compound block.

break statement allows you to ``jump'' out of a compound block --- only for loops and switch blocks.

Example:

int n;

cout << "Enter n: ";
cin << n;

switch (n)
{
 case 1:
 case 2:
   cout << "**\n";
   break;

 case 3:
   cout << "***\n";
   break;

 case 4:
 case 5:
 case 6:
   cout << "****\n";
   break;

 default:
   cout << "******\n";
   break;
}

Exercises

Break up into groups for exercises 2, 6, 7, and 10 on pg. 421:

How would you solve programming problem 1 on pg. 422?



Thomas P. Kelliher
Tue Apr 16 12:15:35 EDT 1996
Tom Kelliher