Monday, 22 April 2019

Do While Loop in C

While loop and do while loop in C is similar, the basic difference is that the test-condition in the while loop checks on the initial stage whereas in the do-while loop, the test-condition is defined at the bottom due to which the do-while loop runs at least once.


Do-while loop in C

Syntax of the do while loop in C

do
{
Body statements;
} while (test_condition);



Flow Diagram of do while loop in C

do while loop in C
Flow diagram of do while loop in C

Without checking test condition, the loop is executed at least once, after that test condition inside the while loop is evaluated, if it is true then loop body will execute otherwise. Let's try to understand this concept with the help of the program,

A Program which prints the value from 1 to 5.

#include <stdio.h>
int main( )
{
    int i=0;
    do
    {
      i++;
      printf ("output %d\n",i);
    }while(i<5);
    return 0;
}

Output
Output 1
Output 2
Output 3
Output 4
Output 5

Explanation
In the above program, the variable 'i' is initiated to 0. Now, the loop body is executed at least once. Variable 'i' is incremented to 1, after that output is printed. Now, test-condition (i<5) is evaluated, if this condition is true then output is occurring otherwise.

Do while loop without body

#include <stdio.h>
int main ( )
{
    int i=0;
    printf ("Hello World");
    do
    {

    }while(i<5);
    return 0;
}

Output
Hello World

Infinite do while loop in C

Example 1
#include <stdio.h>
int main( )
{
do
{
printf ("Infinite do while loop in C");
}while(1);
return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
:
:
:
:
:
up to infinity

Example 2
#include <stdio.h>
int main ( )
{
    do
    {
        printf ("Infinite do while loop in C\n");
    }while(11>1);
    return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
.
.
.
.
.
.
.
.
.
.
.
.
up to infinity

Example 3
#include <stdio.h>
int main ( )
{
    int i=10;
    do
    {
        i--;
        printf ("Infinite do while loop in C\n");
    }while (i<11);
    return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
.
..
.
..
.
.
up to infinity