The do-while loop
is similar to the while loop, except that
the test condition occurs at the end of the loop.
Having the test condition at the end, guarantees that the
body of the loop always executes at least one time. The format of the do-while
loop is shown in the box at the right.
The test condition must be
enclosed in parentheses and FOLLOWED BY A SEMI-COLON.
Semi-colons also follow each of the statements within the block. The
body of the loop (the block of code) is enclosed in braces and indented for readability.
(The braces are not required if only ONE
statement is used in the body of the loop.)
The do-while loop is an exit-condition
loop. This means that the body of the loop is always executed
first. Then, the test condition is
evaluated. If the test condition is TRUE, the
program executes the body of the loop again. If the test condition is FALSE,
terminates and program execution continues with the statement following the while.
/*The following program fragment is
an input routine that insists that the user type a correct response -- in this
case, a small case or capital case 'Y' or 'N'. The
do-while loop guarantees that the body of the loop (the question) will always execute at least
cout<< "Do you want to
cout<< "You must type a 'Y' or
cin >> ans;
while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans
/*the loop continues until the user
enters the correct response*/