OCJP

Do. While Loop in C Language

We have discussed while loop in our earlier post. There is another loop for same purpose is do.while. Do.. While is an exit control loop. Exit control means condition is placed at last so iteration executes at least single time even if condition is false. Condition statement in do while ends with ;.

do
{
}while(condition);

Example

#include<stdio.h>
#include<conio.h>
void main()
{
	int i=100; //Initial Value
	clrscr();
	do
	{
	printf("%d ",i);
	i+=10;// change in variable
	}while(i<=200); //condition

getch();
}

Output will be : 100 110 120 130 140 150 160 170 180 190 200

In above example there is no difference in output with while or do..while. But in below mentioned example condition is false, even if output will be 300. Means at least single time it is executed.

#include<stdio.h>
#include<conio.h>
void main()
{
	int i=300; //Initial Value
	clrscr();
	do
	{
	printf("%d ",i);
	i+=10;// change in variable
	}while(i<=200); //condition

getch();
}

In short

Entry Control loop (While/for) does not execute if condition is false.

Exit Control Loop (do..while) executes at least single time even if condition is false.

No ; is placed in for/while but there is ; after condition in do..while.

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?