What is do-while loop?

do-while loop in c is a loop control statement that executes a block of statement repeatedly until a certain condition is met.

It is similar to a while statement but here condition is checked after the execution of statements. Hence the block of statements is executed at least once.

Syntax

do
{
  statements;
}while(condition);

How does do-while loop works?

Here the loop variable is defined before do-while statement.

Then the block of statements is executed. Afterward, the condition is checked. If it becomes true then control goes back and executes a block of statements otherwise it terminates the loop.

The update statement is written inside the loop body.


Do-while loop in c example program

Example 1

//do-while loop in c example program 2
#include<stdio.h>
int main()
{
  int i=0;
  do
   {
     printf("%d \n",i);
     i++;
   }while(i<=10);
  return 0;
}
	0 	1 	2 	3 	4 	5 	6 	7 	8 	9 	10 
do while loop example program

Code explanation

First we define loop variable.

As the loop executes loop variable is incremented.

At the end of each iteration, the condition is checked. If the condition is true then the statements inside the loop are executed otherwise the loop terminates.

The process continues until loop variable i value becomes 10.

Example 2

//do while loop in c example program 2
#include<stdio.h>
int main()
{
  int i=10;
  do
   {
     printf("%d \n",i);
     i--;
   }while(i>=0);
  return 0;
}
	10 	9 	8 	7 	6 	5 	4 	3 	2 	1 	0 
do while loop example program 2

Code explanation

First we define loop variable that is i.

Statement written inside do-while loop executes before condition is checked.

Here loop variable is decremented in each iteration.

Condition is checked in each iteration. If the condition is true then the statements inside the loop are executed otherwise the loop terminates.

The process continues until i value becomes 0.


People also ask for

What is do-while in c?

do-while is a loop control statement that executes a block of statement repeatedly until a certain condition is met. It is similar to a while statement but here condition is checked after the execution of statements. Hence the block of statements is executed at least once.


People also read