11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5: Controlling Program Flow 65the body of the loop (the body is the code between the braces) where it decrementsloopCount by 1 and outputs the result to the display. The programthen returns to the top of the loop to test whether loopCount is still positive.When executed, the program WhileDemo outputs the results shown in thisnext snippet. Here I entered a loop count of 5. The result is that the programloops 5 times, each time outputting a countdown.Enter loopCount: 5Only 4 loops to goOnly 3 loops to goOnly 2 loops to goOnly 1 loops to goOnly 0 loops to goPress any key to continue . . .If the user enters a negative loop count, the program skips the loop entirely.That’s because the specified condition is never true, so control never entersthe loop. In addition, if the user enters a very large number, the program loopsfor a long time before completing.A separate, less frequently used version of the while loop known as thedo . . . while appears identical except the condition isn’t tested untilthe bottom of the loop:do{// ...the inside of the loop} while (condition);Because the condition isn’t tested until the end, the body of the do . . .while is always executed at least once.The condition is only checked at the beginning of the while loop or at theend of the do . . . while loop. Even if the condition ceases to be true atsome time during the execution of the loop, control does not exit the loopuntil the condition is retested.Using the autoincrement/autodecrement featureProgrammers very often use the autoincrement ++ or the autodecrement --operators with loops that count something. Notice, from the following snippetextracted from the WhileDemo example, that the program decrements theloop count by using assignment and subtraction statements, like this:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!