The while and do-while loops in C

Apart from for loops, we also have two other loops - while loop and the do while loop.They do the same work as the for loop and differ in their syntax only.

The while loop

The syntax of the while loop is as follows :

    while(condition is false)
    {
        //Statements
    }
            
While the termination condition is false, the statements inside the while loop are executed. When the condition becomes true, the while loop is terminated and the control comes out of the body of the loop. Here, the declaration of the variable is done before the start of the loop and the updation happens inside the body of the loop. For example -

    #include <stdio.h>
    void main()
    {
      int i=1;   //initialization
      while(i < 6)
      {
        printf("%d ",i);
        i++;    //increment i by one
      }
    }
    

Output

    1 2 3 4 5
    
It prints all the numbers from 1 to 5.

The do while loop

It is very similar to the while loop except the fact that it executes for minimum one time even if the termination condition is false at the start of the loop.The reason behind this is that it checks the condition at the end, unlike the while loop. It first executes the statements and then checks the condition.For example -

    #include <stdio.h>
    void main()
    {
      int i=1;
      do{
      printf("%d ",i);
      i++;
      }while(i < 6);
    }            
                

Output

    1 2 3 4 5
    
Here, it gave the same output as while loop but not in all cases. To better understand the difference between the two loops, check the following section.

Example of while loop


        #include <stdio.h>
        void main()
        {
          int i=6;   
          while(i < 6)
          {
            printf("%d ",i);
            i++;   
          }
          printf("Value of i after coming out of while loop = %d",i);
        }
      

Output

    Value of i after coming out of while loop = 6
    

Example of do while loop


        #include <stdio.h>
        void main()
        {
          int i=6;   
          do
          {
            printf("%d ",i);
            i++;   
          }while(i < 6);
          printf("Value of i after coming out of while loop = %d",i);
        }
        

Output

    6 Value of i after coming out of while loop = 7
    
As you can see if we use the while loop and the condition is false, it did not go inside the loop. However, in the case of do while loop, even if the condition was false, it still executed the statements once.