Sams Teach Yourself C++ in 21 Days

(singke) #1
19: case 1: cout << “Incredible!” << endl;
20: break;
21: default: cout << “Too large!” << endl;
22: break;
23: }
24: cout << endl << endl;
25: return 0;
26: }

Enter a number between 1 and 5: 3
Excellent!
Masterful!
Incredible!

Enter a number between 1 and 5: 8
Too large!
The user is prompted for a number on lines 9 and 10. That number is given to the
switchstatement on line 11. If the number is 0 , the casestatement on line 13
matches, the message Too small, sorry!is printed, and the breakstatement on line 14
ends the switch. If the value is 5 , execution switches to line 15 where a message is
printed, and then falls through to line 16, another message is printed, and so forth until
hitting the breakon line 20, at which time the switch ends.
The net effect of these statements is that for a number between 1 and 5, that many mes-
sages are printed. If the value of number is not 0 to 5, it is assumed to be too large, and
the default statement is invoked on line 21.

OUTPUT


200 Day 7


LISTING7.16 continued

ANALYSIS

The switchStatement
The syntax for the switchstatement is as follows:
switch (expression)
{
case valueOne: statement;
case valueTwo: statement;
....
case valueN: statement;
default: statement;
}
The switchstatement allows for branching on multiple values of expression. The expres-
sion is evaluated, and if it matches any of the casevalues, execution jumps to that line.
Execution continues until either the end of the switchstatement or a breakstatement is
encountered.
Free download pdf