Sams Teach Yourself C++ in 21 Days

(singke) #1
whether counterhas gone past 10. If it hasn’t, the whileloop iterates. If counteris
greater than 10, the break on line 13 ends the whileloop, and program execution falls
through to line 15, where the results are printed.
This program works, but it isn’t pretty. This is a good example of using the wrong tool
for the job. The same thing can be accomplished by putting the test of counter’s value
where it belongs—in the whilecondition.

184 Day 7


Eternal loops such as while (true)can cause your computer to hang if
the exit condition is never reached. Use these with caution and test them
thoroughly.

CAUTION

C++ gives you many ways to accomplish the same task. The real trick is picking the
right tool for the particular job.

DOuse whileloops to iterate while a
condition is true.
DOexercise caution when using con-
tinueand breakstatements.
DObe certain your loop will eventually
end.

DON’Tuse the gotostatement.
DON’T forget the difference between
continueand break. continuegoes to
the top; breakgoes to the bottom.

DO DON’T


Implementing do...whileLoops ........................................................................


It is possible that the body of a whileloop will never execute. The whilestatement
checks its condition before executing any of its statements, and if the condition evaluates
false, the entire body of the whileloop is skipped. Listing 7.6 illustrates this.

LISTING7.6 Skipping the Body of the whileLoop
1: // Listing 7.6
2: // Demonstrates skipping the body of
3: // the while loop when the condition is false.
4:
5: #include <iostream>
6:
Free download pdf