Do While Loop in C

Introduction

There is no big difference between the ‘do….while’ loop from the other loops like ‘for’ and ‘while’. The only difference is that the code written in the body of this loop is executed once before verifying the condition. In this article we will explore Do While Loop in C.

Syntax: do

             {

                  statement(s)

              }

               While (condition);

Now, let us start coding with the same program with the ‘for’ and ‘while’ loop, but this time, we will use the ‘do….while’ loop.

Example of Do While Loop in C

#include<stdio.h>

int main()

{

            int m=1;

            do

            {

                        printf("Good morning\n");

                        m++;

            }

            while(m<=10);

            return 0;

}

 

Output

Do While Loop in C

Explanation

See, ‘m’ is first declared and initialised with 1.

Then, the ‘do…while’ loop begins. ‘Good morning’ text is printed once before there is a condition check. After that, the next statement increases ‘m’ by 2. Coming out of ‘{}’ braces, there is a condition written in ‘()’ followed by the ‘while’ keyword.

The condition is true for ‘m=2’. Again, the loop begins, and the same text is printed once more. Then, the value of ‘m’ is increased to 3.

This process continues, and when ‘m’ is updated to 10, the ‘good morning’ text is printed for the 10th time. ‘m++’ increases the value of m to 11, but this will make the condition false. Thus, the loop terminates.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.