Home >>C Tutorial >C do-while loop
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'); }
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; }
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; }
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);