|
|
|
|
|
|
|
Analysis: This program is a game. Enter two numbers, one small and one large. The smaller number will count up by ones; the larger number will count down by twos. The goal of the game is to guess when they'll meet. |
|
|
|
|
|
|
|
|
On lines 1215, the numbers are entered. Line 20 sets up a while loop, which will continue only as long as three conditions are met: |
|
|
|
|
|
|
|
|
small is not bigger than large. |
|
|
|
|
|
|
|
|
small doesn't overrun the size of a small integer (MAXSMALL). |
|
|
|
|
|
|
|
|
On line 23 the value in small is calculated modulo 5,000. This does not change the value in small, however; it only returns the value 0 when small is an exact multiple of 5,000. Each time it is, a dot (.) is printed to the screen to show progress. On line 26, small is incremented, and on line 28 large is decremented by 2. |
|
|
|
|
|
|
|
|
When any of the three conditions in the while loop fails, the loop ends and execution of the program continues after the while loop's closing brace on line 27. |
|
|
|
|
|
|
|
|
At times, you'll want to return to the top of a while loop before the entire set of statements in the while loop is executed. The continue statement jumps back to the top of the loop. |
|
|
|
|
|
|
|
|
At other times, you might want to exit the loop before the exit conditions are met. The break statement immediately exits the while loop, and program execution resumes after the closing brace. |
|
|
|
|
|
|
|
|
Listing 8.4 demonstrates the use of these statements. This time the game has become more complicated. The user is invited to enter a small number, a large number, a skip number, and a target number. The small number will be incremented by 1, and the large number will be decremented by 2. The decrement will be skipped each time the small number is a multiple of the skip. The game ends if small becomes larger than large. If the large number reaches the target exactly, a statement is printed and the game stops. |
|
|
|
|
|
|
|
|
The user's goal is to put in a target number for the large number that will stop the game. |
|
|
|
|
|
|
|
|
LISTING 8.4breakANDcontinue |
|
|
|
 |
|
|
|
|
1: // Listing 8.4
2: // Demonstrates break and continue
3: |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|