Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 187

7


The do...whileStatement
The syntax for the do...whilestatement is as follows:
do
statement
while (condition);
statementis executed, and then conditionis evaluated. If conditionis true, the loop is
repeated; otherwise, the loop ends. The statements and conditions are otherwise identi-
cal to the whileloop.
Example 1
// count to 10
int x = 0;
do
cout << “X: “ << x++;
while (x < 10)
Example 2
// print lowercase alphabet.
char ch = ‘a’;
do
{
cout << ch << ‘ ‘;
ch++;
} while ( ch <= ‘z’ );

DOuse do...whilewhen you want to
ensure the loop is executed at least once.
DOuse whileloops when you want to
skip the loop if the condition is false.
DOtest all loops to be certain they do
what you expect.

DON’Tuse breakand continuewith
loops unless it is clear what your code is
doing. There are often clearer ways to
accomplish the same tasks.
DON’T use the gotostatement.

DO DON’T


Looping with the forStatement ..........................................................................


When programming whileloops, you’ll often find yourself going through three steps:
setting up a starting condition, testing to see whether the condition is true, and incre-
menting or otherwise changing a variable each time through the loop. Listing 7.8 demon-
strates this.
Free download pdf