In a while loop, the test expression is evaluated at the
beginning of the loop. If the test expression is false, the
loop body is not executed at all.
If the loop body must be executed at least once, then the
do..while construct should be used. The do..while construct
places the test expression at the end of the loop.
Program 2.2 can be modified using the do..while loop in the
//This program calculate the square of interger numbers
int iNum, iSquare;
cout<<"Enter a number:";
iSquare = iNum * iNum;
cout<<"The square of "<<iNum<<"is"<<iSquare<<endl;
cout<<"Do you want to input another number(y/n)?";
while(cReply != 'n');
used. The do..while construct places the test expression at
the end of the loop.
The keyword do marks the beginning of the loop. The braces
delimit the body of the loop. Finally, a while statement
provides the test expression and terminates the loop.
The sample output of Program 2.3 is:
Enter a number: 4
The square of 4 is 16
Do you want to input another number(y/n)?n
If the user enters 'n', the test expression becomes false
and the loop terminates.