Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 201

7


Using a switchStatement with a Menu ........................................................


Listing 7.17 returns to the for(;;)loop discussed earlier. These loops are also called
forever loops, as they will loop forever if a break is not encountered. In Listing 7.17, the
forever loop is used to put up a menu, solicit a choice from the user, act on the choice,
and then return to the menu. This continues until the user chooses to exit.


If expressiondoes not match any of the casestatements, and if there is a defaultstate-
ment, execution switches to the defaultstatement, otherwise the switchstatement
ends.
Example 1
switch (choice)
{
case 0:
cout << “Zero!” << endl;
break;
case 1:
cout << “One!” << endl;
break;
case 2:
cout << “Two!” << endl;
default:
cout << “Default!” << endl;
}
Example 2
switch (choice)
{
case 0:
case 1:
case 2:
cout << “Less than 3!”;
break;
case 3:
cout << “Equals 3!”;
break;
default:
cout << “greater than 3!”;
}
Free download pdf