Sams Teach Yourself C++ in 21 Days

(singke) #1
Enter a small number: 2
Enter a large number: 20
Enter a skip number: 4
Enter a target number: 6

skipping on 4
skipping on 8

Small: 10 Large: 8
In this play, the user lost; smallbecame larger than largebefore the target num-
ber of 6 was reached.
On line 26, the whileconditions are tested. If smallcontinues to be smaller than large
and if smallhasn’t overrun the maximum value for a small int, the body of the while
loop is entered.
On line 30, the small value is taken modulo the skip value. If smallis a multiple of skip,
the continuestatement is reached and program execution jumps to the top of the loop
back at line 26. This effectively skips over the test for the target and the decrement of
large.
On line 36,targetis tested against the value for large. If they are the same, the user
has won. A message is printed and the breakstatement is reached and executed. This
causes an immediate break out of the whileloop, and program execution resumes on
line 44.

OUTPUT


182 Day 7


ANALYSIS

Both continueand breakshould 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
continueand breakcan render even a small whileloop unreadable.
A need for breaking within a loop often indicates that the terminating con-
dition of the loop has not been set up with the appropriate Boolean expres-
sion. It is often better to use an ifstatement within a loop to skip some
lines than to use a breaking statement.

NOTE

The continueStatement
continue;causes a while,do...while, or forloop to begin again at the top of the loop.
See Listing 7.4 for an example of using continue.
Free download pdf