do while loop

We have to use do while loop when we need to execute a group of statements at least once.

Only difference between while and do while loop is that while loop will execute statements only when given condition is true whereas do while will execute statements at least once without checking the condition.

Example

Get integer input from user and print it until the input is 100.

Here, we should get at least one input from the user. So, that only we can check whether it is 100 or not.

These kind of situation we should go for do while loop.

Syntax

do
{
    //statements
    in(de)crement variable
}while(condition);

1.It will execute the statements

2.And then checks for condition

3.If condition is true

4.Execution will goto step 1 again

5.else

6.Execution will come out of the do while loop





Sample program

Get input from the user and print it until the input is 100.

Example

#include<stdio.h>

int main()
{
    int num;

    do
    {
        scanf("%d",&num);    //getting input from user
        printf("%d\n",num); //Printing the number

     }while(num != 100); //if the input is 100, loop will terminate

     return 0;
}


Topics You Might Like