C++

THE DO...WHILE STATEMENT

The syntax for the do...while statement is as follows:

do

statement

while (condition);

statement is executed, and then condition is evaluated. If condition is TRUE, the loop is repeated; otherwise, the loop ends. The statements and conditions are otherwise identical to the while loop. 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’ );

DO use do...while when you want to ensure the loop is executed at least once. DO use while loops when you want to skip the loop if the condition is false. DO test all loops to make sure they do what you expect.

Back to Index