do while loop in C

To execute a part of program or code several times, we can use do-while loop of C language. The code given between the do and while block will be executed until condition is true.

In do while loop, statement is given before the condition, so statement or code will be executed at lease one time. In other words, we can say it is executed 1 or more times.

It is better if you have to execute the code at least once.

do while loop syntax

The syntax of C language do-while loop is given below:

 
  • do{  
  • //code to be executed  
  • }while(condition);  

Flowchart of do while loop

do while loop

 


 

do while example

There is given the simple program of c language do while loop where we are printing the series from 1 to 20.

 
  • #include<stdio.h>  
  • int main(){    
  • int i=1;      
  • do{    
  • printf(“%d \n”,i);    
  • i++;    
  • }while(i<=20);   
  • return 0;  
  • }     

Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Program to print table for the given number using do while loop

 
  • #include<stdio.h>  
  • int main(){    
  • int i=1,number=0;    
  • printf(“Enter a number: “);    
  • scanf(“%d”,&number);    
  • do{    
  • printf(“%d \n”,(number*i));    
  • i++;    
  • }while(i<=10);    
  • return 0;  
  • }    

Output

Enter a number: 6
6
12
18
24
30
36
42
48
54
60
Enter a number: 10
10
20
30
40
50
60
70
80
90
100

Infinitive do while loop

If you pass 1 as a expression in do while loop, it will run infinite number of times. Because 1 is considered to be true always

 
  • do{  
  • //statement  
  • }while(1);