C++ Do While Loop

The Do While Loop is different from the While Loop for one reason only. The condition is checked after executing the statements. Therefore, this loop guarantees that the statements will be executed at least once.

Do While Loop

Do While Loop

The syntax for the Do While Loop is below:

do { 
 
// Statements ...
 
} while ( condition );

Do While Example

An example of a do while loop is below.

1
2
3
4
5
6
7
string msg;
 
do { 
   cout << "Enter a word or 'exit' to quit: " << endl;
 
   cin >> msg;
} while ( msg != "exit" );

Do While Loops aren’t used as extensively as While Loops and For Loops in practice due to their nature. They are only used for specific cases where the programmer needs the block of statements to be executed at least once.

Going further with Do While Loops

Now that you understand Do While Loops, While Loops, and For Loops why not try the following?

  1. Create a factorial program that uses a while, do while, and for loop. Do the same for summation. This should make you fully understand all loops and when to use them.

Tags: , , ,

  • http://pulse.yahoo.com/_Z7XDURZR6JKF6BHMS2BKMQCGJU Khadija Jamshaid

    it’s very helpful and thanks a lot

  • Sudi Mitali

    how to write a factorial program in c++ (not in c) using do while???

    • http://talkbinary.com Diego Villasenor

      You should try and do factorial using a for loop instead. A do while is not practical because sometimes we don’t need to execute the loop if the value we are computing for is either 0 or 1 which are already known beforehand.