do-while Loop

do while loop in C

The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.

do while loop syntax

The syntax of the C language do-while loop is given below:
  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Example 1

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. void main ()  
  4. {  
  5.     char c;  
  6.     int choice,dummy;    
  7.     do{  
  8.     printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");  
  9.     scanf("%d",&choice);  
  10.     switch(choice)  
  11.     {  
  12.         case 1 :   
  13.         printf("Hello");   
  14.         break;  
  15.         case 2:    
  16.         printf("Javatpoint");  
  17.         break;  
  18.         case 3:  
  19.         exit(0);   
  20.         break;  
  21.         default:   
  22.         printf("please enter valid choice");      
  23.     }  
  24.     printf("do you want to enter more?");   
  25.     scanf("%d",&dummy);  
  26.     scanf("%c",&c);  
  27.     }while(c=='y');  
  28. }  

Output

1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y

1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
n

Flowchart of do while loop

flowchart of do while loop in c language


do while example

There is given the simple program of c language do while loop where we are printing the table of 1.
  1. #include<stdio.h>  
  2. int main(){    
  3. int i=1;      
  4. do{    
  5. printf("%d \n",i);    
  6. i++;    
  7. }while(i<=10);   
  8. return 0;  
  9. }     

Output

1
2
3
4
5
6
7
8
9
10

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

  1. #include<stdio.h>  
  2. int main(){    
  3. int i=1,number=0;    
  4. printf("Enter a number: ");    
  5. scanf("%d",&number);    
  6. do{    
  7. printf("%d \n",(number*i));    
  8. i++;    
  9. }while(i<=10);    
  10. return 0;  
  11. }    

Output

Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100

Infinitive do while loop

The do-while loop will run infinite times if we pass any non-zero value as the conditional expression.
  1. do{  
  2. //statement  
  3. }while(1);  

Comments

Popular posts from this blog

Features of C Language

Flow of C program

Types of LOOPS