< previous page page_465 next page >

Page 465
The Do-While statement
do
{
  Statement1;
  Statement2;
  .
  .
  .
  StatementN;
} while (Expression);
means Execute the statements between do and while as long as Expression is still nonzero (TRUE) at the end of the loop.
Let's compare a While loop and a Do-While loop that do the same task:they find the first period in a file of data. Assume that there is at least one period in the file.
While Solution
dataFile >> inputChar;
while (inputChar != .)
    dataFile >> inputChar;
Do-While Solution
do
    dataFile >> inputChar;
while (inputChar != .);
The While solution requires a priming read so that inputChar has a value before the loop is entered. This isn't required for the Do-While solution because the input statement within the loop is executed before the loop condition is evaluated.
Let's look at another example. Suppose a program needs to read a person's age interactively. The program requires that the age be positive. The following loops ensure that the input value is positive before the program proceeds any further.
While Solution
cout <Enter your age: ;
cin >> age;
while (age <= 0)
{
    cout << Your age must be positive. << endl;
    cout << Enter your age: ;
    cin >> age;
}

 
< previous page page_465 next page >