Tutorial#32 - do...while Looping Repetition Structure

do...while Looping Repetition Structure

do...while looping structure:

          This section describes the third type of looping or repetition structure, called a do. . .while loop. The general form of a do. . .
while statement is as follows:
do
    statement
while (expression);
Of course, statement can be either a simple or compound statement. If it is a compound statement, enclose it between braces.

This Figure shows the flow of execution of a do. . .while loop.

In C++, do and while are reserved words.
The statement executes first, and then the expression is evaluated. If the expression evaluates to true, the statement executes again. As long as the expression in a do...while statement is true, the statement executes. To avoid an infinite loop, you must, once again, make sure that the loop body contains a statement that ultimately makes the expression false and assures that it exits properly.

Example-1:
i = 0;
do
{
   cout << i << " ";
   i = i + 5;
}
while (i <= 20);
The output of this code is:
0 5 10 15 20
After 20 is output, the statement:
i = i + 5;
changes the value of i to 25 and so i <= 20 becomes false, which halts the loop.

In a while and for loop, the loop condition is evaluated before executing the body of the loop. Therefore, while and for loops are called pretest loops. On the other hand, the loop condition in a do. . .while loop is evaluated after executing the body of the loop. Therefore, do. . .while loops are called post-test loops.
Because the while and for loops both have entry conditions, these loops may never activate. The do...while loop, on the other hand, has an exit condition and therefore always executes the statement at least once.

We use this loop because we want to execture some special statements at one time and for next you need to fulfil the loop condition. In some conditions we use this looping structure.
For Example, You give web services to your customers and you give one time limited service to customers and for further ultimate or other services, customer requested to access other services, Then you apply conditions on customer in this way. This is an simple example of do while loop.

Comments