do while loop in C

The do...while construct provides an iterative loop. It is same as the while loop except that it always executes the statement at least once. The statement is executed first and then the conditional expression is evaluated to decide upon further iteration.

Syntax
do {
    //statement (code to be executed)
} while (expression);

Example 1

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

Output

Output
1. Print Hello 2. Print rookienerd 3. Exit 1 Hello do you want to enter more? y 1. Print Hello 2. Print rookienerd 3. Exit 2 rookienerd 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.

snippet
#include
int main(){  
int i=1;    
do{  
printf("%d \n",i);  
i++;  
}while(i<=10); 
return 0;
}

Output

Output
1 2 3 4 5 6 7 8 9 10

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

snippet
#include
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

Output
Enter a number: 5 5 10 15 20 25 30 35 40 45 50
Output
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 or when the value always evaluates to true in the conditional expression.

snippet
do {
    //statement
} while (1);
snippet
do {
    //statement
} while (true);
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +