Home >>C Tutorial >C do-while loop

do while loop in C

Do-while loop in the C language

The do while loop in the C language is basically a post tested loop and the execution of several parts of the statements can be repeated by the use of do-while loop. The main use of the do-while loop is there is a need to execute the loop at least once. The maximum use of the do-while loop lies in the menu-driven programs where the termination condition generally depends upon the end user.

Here is the syntax of the do while loop in the C language:

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

Here is an example of the same:

#include<stdio.h>  
#include<stdlib.h>  
void main ()  
{  
    char c;  
    int choice,dummy;    
    do{  
    printf("\n1. Print Hi\n2. Print Phptpoint\n3. Endt\n");  
    scanf("%d",&choice);  
    switch(choice)  
    {  
        case 1 :   
        printf("Hi");   
        break;  
        case 2:    
        printf("Phptpoint");  
        break;  
        case 3:  
        exit(0);   
        break;  
        default:   
        printf("please input the valid choice");      
    }  
    printf("want to enter more?");   
    scanf("%d",&dummy);  
    scanf("%c",&c);  
    }
	while(c=='y');  
}  
Output :
1. Print Hi 2. Print Phptpoint 3. End 1 Hi want to enter more? y 1. Print Hi 2. Print phptpoint 3. Exit 2 Phptpoint want to enter more? n

Here is the Flow Chart of the do-while:

Here are the do while loop examples to get a better understanding of the subject:

1. In the following example, we are basically trying to print the table of 1:

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

2. Here is another example of do-while loop in which we are trying to print the table for a given number that is entered by the end user:

#include<stdio.h>  
int main()
{    
int i=1,number=0;    
printf("Please enter the number of your choice: ");    
scanf("%d",&number);    
do{    
printf("%d \n",(number*i));    
i++;    
}
while(i<=10);    
return 0;  
}    
Output :
Please enter the number of your choice: 3
3 6 9 12 15 18 21 24 27 30

Infinitive do while loop in the C language

This type of the do-while loop is known to execute the code for an infinite number of times if the user enters any non-zero value as the conditional expression.

Here is the syntax of the infinite do-while loop in the C language:

do
{  
//statement  
}
while(1);  

Popular Tutorials