Difference between while & do-while in C Programming
- Tech Area
- May 11, 2024
In this tutorial, We will see the difference between while & do-while in C programming language.
while loop
The syntax of the while
loop is:
while (TestExpression) {
// the body of the loop
}
How while loop works?
The while
loop evaluates the TestExpression
inside the parentheses ()
.
If TestExpression
is true, statements inside the body of while
loop are executed. Then, TestExpression
is evaluated again.
The process goes on until TestExpression
is evaluated to false. If TestExpression
is false, the loop terminates.
Program to print numbers using while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int a=1;
clrscr();
while(a<=5)
{
printf("%d\n", a);
a++;
}
getch();
}
Output
1
2
3
4
5
Here, we have initialized a
to 1.
When a = 1
, the test expression a <= 5
is true. Hence, the body of the while
loop is executed. This prints 1
on the screen and the value of a
is increased to 2
.
Now, a = 2
, the test expression a <= 5
is again true. The body of the while
loop is executed again. This prints 2
on the screen and the value of a is increased to 3
.
This process goes on until a
becomes 6. Then, the test expression a <= 5
will be false and the loop terminates.
do while loop
The do while
loop is similar to the while
loop with one important difference. The body of do while
loop is executed at least once. Only then, the test expression is evaluated.
The syntax of the do while
loop is:
do {
// the body of the loop
}
while (TestExpression);
How do while loop works?
The body of do while
loop is executed once. Only then, the TestExpression
is evaluated.
If TestExpression
is true, the body of the loop is executed again and TestExpression
is evaluated once more.
This process goes on until TestExpression
becomes false. If TestExpression
is false, the loop terminates.
Program to print numbers using do while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int a=1;
clrscr();
do
{
printf("%d\n", a);
a++;
}
while(a<=0);
getch();
}
Output
1
Here, we have initialized a
to 1.
This prints 1
on the screen and the value of a
is increased to 2
and then condition is checked. The test expression a <=
0 will be false and the loop terminates.
The do while
loop executes at least once i.e. the first iteration runs without checking the condition. The condition is checked only after the first iteration has been executed.
Join 10,000+ subscriber