< previous page page_129 next page >

Page 129
LISTING 8.15 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
19:       case 1:  cout < Incredible!\n;
20:                break;
21:       default: cout < Too large!\n;
22:                break;
23:    }
24:    cout < \n\n;
25:    return 0;
26: }

Output:
Enter a number between 1 and 5:  3
Excellent!
Masterful!
Incredible!
Enter a number between 1 and 5: 8
Too large!
Analysis: The user is prompted for a number. That number is given to the switch statement. If the number is 0, the case statement on line 13 matches, the message Too small, sorry! is printed, and the break statement 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 where another message is printed, and so forth until hitting the break on line 20.
The net effect of these statements is that, for a number 05, many messages are printed. If the value of number is not 05 it is assumed to be too large, and the default statement is invoked on line 21.
Summary
There are a number of different ways of causing a C++ program to loop. while loops check a condition, and if it is true, execute the statements in the body of the loop. dowhile loops execute the body of the loop and then test the condition. for loops initialize a value and then test an expression. If expression is true, the final statement in the for header is executed, as is the body of the loop. Each subsequent time through the loop, the expression is tested again.
The goto statement is generally avoided, because it causes an unconditional jump to a seemingly arbitrary location in the code, thus making source code difficult to understand and maintain. continue causes while, dowhile, and for loops to start over, and break causes while, dowhile, for, and switch statements to end.

 
< previous page page_129 next page >

If you like this book, buy it!