do-while Loop

  • while loop is also called exit control loop, because  condition is checked at the last.
  • Condition is checked at the end ,so it means weather the condition for the first
    iteration is false it will execute the code which is written in the block
  • After execution again condition will be checked and body of loop going to be executed again.
  • It will perform same task repeatedly until the condition gets false.
  • if you want to stop loop at certain point then
    You can terminated(stop) the loop by using break keyword.
  • Soon we will going to cover break keyword in our further modules.

Syntax:

do
{
// body for  'do while' block.

}while(condition);      //condition is checked at the end.

Let's see program of printing numbers from 1 to 5 from do-while.

#include<stdio.h>

void main()
{
int i=1;        //initializing the variable 
do 
{

printf("%d\n",i);           
i++;                          //incrementing  the variable by 1.
}while(i <= 5);           //checking the condition. 

}

Output:

1
2
3
4
5
  • Step by Step Explanation.
  • First value of i will get print, and i will get increment by 1 and condition get checked.
  • If condition evaluated to true, it will print the value of incremented variable.
  • Again, condition will get check if evaluated to true it will print the incremented value of i.
  • Above steps , will repeat until the condition gets evaluated to false.
  • In this example, for value of i = 6 ,loop will get terminate(stop) and control will go to the next piece of code.
  • Control will not stay within the do-while loop.

Lets see behaviour of do while loop.

#include<stdio.h>

void main()
{
int i=6;        //initializing the variable 
do 
{

printf("%d\n",i);           
i++;                          //incrementing  the variable by 1.
}while(i <= 5);           //checking the condition. 

}

Output:

6
  • Even though variable 'i' was greater than 5,it printed the value.
  • After printing the variable , it was incremented by 1,which became 7
  • then First time condition was checked, as  i has become 7 ,so condition evaluated as false and loop gets terminated(stop).
  • Even then it had printed the value of i, because  In do-while loop, condition is checked at the end
  • Even if the Condition is false ,it will evaluate the code for First time and then it will get terminated.
  • So that is why, It is known as exit control loop, condition is checked at the end.