While and Do...while loop

While and Do...while loop


While Loop
Do…While loop

While loop is entry controlled loop.
Do…while is exit controlled loop.
If condition is false, statements are not executed.
Even if condition is false, statements are executed once.
There is no semicolon after while(condition)
There is semicolon after while(condition);
Syntax:
while(condition)
{
}
Syntax:
do
{
}
while(condition);

Let’s see program to get clarity:

#include<stdio.h>
void main()
{
int a=1;
while(a<=10)
{
printf(“Hello”);
}
}

#include<stdio.h>
void main()
{
int a=1;
do
{
printf(“Hello”);
}
while(a<=10);
}

Both programs will print Hello 10 times.
But,
For below case,


#include<stdio.h>
void main()
{
int a=20;
while(a<=10)
{
printf(“Hello”);
}
}

#include<stdio.h>
void main()
{
int a=20;
do
{
printf(“Hello”);
}
while(a<=10);
}

Here, while loop will notice that condition is false and will not print hello even once.
But, in do…while loop, Hello will be printed once. Since,  condition is checked at end.


No comments:

Post a Comment