DO…WHILE Loop

Definition:

  • DO…WHILE Loop is a Post-Test loop where condition is tested at the end.
  • DO…WHILE Loop belongs from Unbounded loop where number of executions is indefinite.
  • DO…WHILE loop is also known as Exit Controlled Loop where condition is tested after the executions of the body of a loop.
  • WHILE Loop and DO…WHILE Loop is similar to one another except in case of WHILE Loop condition is checked at the start of the body of loop where as in case of DO…WHILE condition is checked at the end of the body of loop.
  • DO…WHILE Loop gives assurance that to execute the body of a loop at least one time.

Syntax:

      The basic syntax of the DO…WHILE Loop in C-Language

               do

                    {

                           // Body of the loop

                     }

                 while(condition);

How DO…WHILE Loop Works:

  1. The body of the DO…WHILE Loop executed at least once then only condition is evaluated.
  2. If the condition of DO…WHILE Loop is true then only the body of the loop is executed again.
  3. This process continue until the condition becomes false.
  4. Once the condition becomes false then DO…WHILE Loop gets terminated.

Illustration of DO…WHILE Loop

Program: Write a C program to print value of variable from 0 to 3.

#include<stdio.h>

int main()

{

    int a=0;

    do

      {

           printf(“ Value of Integer Variable a is: %d\n”, a)

            a++;

        }

     while(a<=3);

return 0;

}

Output:

Value of Integer Variable a is: 0

Value of Integer Variable a is: 1

Value of Integer Variable a is: 2

Value of Integer Variable a is: 3

Application:

DO…WHILE Loop mostly used in such case where we want to execute the body of the loop at least once.

DO…WHILE Loop used in Menu-Driven programs where condition depends upon the user or programmer.