do while loop in C

Till now we have learnt the most frequently used loops in C programming which are for and while loop. Now lets learn about the third loop control instruction which is do while loop.

do while loop is just like a normal loop control instruction which executes a set of statements until the condition turns false.

do while loop in C

Till now we have learnt that loops checks the condition first before executing the set of statements inside its body. But this loop is a bit different than others. It is compulsory that the statements under the body of do while loop will get executed at least once in a program. This loop control instruction executes its statements first, after that it checks the condition for it.

Why do we use do while loops?

Well that’s a really silly question. You cannot predict anything before programming some big thing. While writing some complex big programs, there is a need of a loop which will execute statements at least once. That’s why do while loop is introduced in C.

Syntax

do
{
do this
and this atleast once!
}while(condition);

Flowchart of do while loop in C – Image Source



Note: Remember writing semi colon after while keyword in do while loop. This is the most common mistake of a beginner C programmer.

Lets make one program to grasp this loop too.

#include<stdio.h>

void main()
{
	do
	{
		printf("OMG its working!");
	}while(7>10);
}

Output

do while in C - Output

Explanation

Well it’s a very simple program to demonstrate the use of do while loops. As you can see the condition is wrong with while keyword. But still the printf() function will get executed once.

Usage of break and continue with do while loop

break: It will work similar to other loops. By introducing break keyword it will take control outside the loop. Remember it is not recommended to use break keyword inside loops without if statement.

continue: The functioning of continue will also work similar to other ones. However do while loop can make some good twist to the programs, if used properly with continue keyword.

This is the last loop control instruction of C programming. I recommend to try your hands on do while loops too. In the next tutorial I will tell you the best way to make Menu in C programming.

Leave a Comment

Your email address will not be published. Required fields are marked *