Sams Teach Yourself C++ in 21 Days

(singke) #1
On lines 12–15, the numbers are entered. Line 20 sets up a whileloop, which will con-
tinue only as long as two conditions are met:


  1. Small is not bigger than large.

  2. Small doesn’t overrun the size of a small integer (MAXSMALL).
    On line 22, the value in smallis calculated modulo 5,000. This does not change the
    value in small; however, it only returns the value 0 when smallis an exact multiple of
    5,000. Each time it is, a dot (.) is printed to the screen to show progress. On line 25,
    smallis incremented, and on line 26,largeis decremented by 2.
    When either of the two conditions in the whileloop fails, the loop ends and execution of
    the program continues after the whileloop’s closing brace on line 27.


180 Day 7


The modulus operator (%) and compound conditions were covered on Day 3,
“Working with Variables and Constants.”

NOTE

Introducing continueand break....................................................................


At times, you’ll want to return to the top of a whileloop before the entire set of state-
ments in thewhileloop is executed. The continuestatement 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
breakstatement immediately exits the whileloop, and program execution resumes after
the closing brace.
Listing 7.4 demonstrates the use of these statements. This time, the game has become
more complicated. The user is invited to enter a small number and a large number, a skip
number, and a target number. The small number will be incremented by one, 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 smallbecomes 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.
Free download pdf