C++ Learning Resource Network!

 
 
 
 C++ Tutorials  >  Variables, Construct & Looping  >  Loop Construct   > do..while loop
 

do..while Loop

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 following way:

//Program 2.3
//This program calculate the square of interger numbers
#include<iostream.h>
void main()
{
char cReply;
int iNum, iSquare;
do
{
cout<<"Enter a number:";
cin>>iNum;
iSquare = iNum * iNum;
cout<<"The square of "<<iNum<<"is"<<iSquare<<endl;
cout<<"Do you want to input another number(y/n)?";
cin>>cReply;
}
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.

 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.