< previous page page_117 next page >

Page 117
Enter a skip number: 4
Enter a target number: 6
skipping on 4
skipping on 8
Small: 10 Large: 8
Analysis: In this play, the user lost; small became larger than large before the target number of 6 was reached.
On line 26, the while conditions are tested. If small continues to be smaller than large, large is larger than 0, and small hasn't overrun the maximum value for an unsigned short int, the body of the while loop is entered.
On line 32, the small value is taken modulo the skip value. If small is a multiple of skip, the continue statement is reached and program execution jumps to the top of the loop at line 26. This effectively skips over the test for the target and the decrement of large.
On line 38, target is tested against the value for large. If they are the same, the user has won. A message is printed, and the break statement is reached. This causes an immediate break out of the while loop, and program execution resumes on line 46.
Both continue and break should be used with caution. They are the next most dangerous commands after goto, for much the same reason. Programs that suddenly change direction are harder to understand, and liberal use of continue and break can render even a small while loop unreadable.
while (1) Loops.
The condition tested in a while loop can be any valid C++ expression. As long as that condition remains true, the while loop will continue. You can create a loop that will never end by using the number 1 for the condition to be tested. Because 1 is always true, the loop will never end, unless a break statement is reached. Listing 8.5 demonstrates counting to 10 using this construct.
LISTING 8.5while (1) LOOPS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:    // Listing 8.5
2:    // Demonstrates a while true loop
3:
4:    #include <iostream.h>
5:
6:    int main()
7:    {
8:      int counter = 0;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_117 next page >

If you like this book, buy it!