The while is a control loop statement in C programming language. It works on validating the test condition which is given to it. While loop evaluated the given conditions, if the condition is true, then the body of the while loop will be executed.

And If the condition is false, then the body of the while loop will be skipped.

These condition checks are performed by again and again till the conditions validate and each time body of while loop gets executed.

Execution of the body will continue until the test condition gets failed and return false. After the failing of test condition control will be transferred out of the loop.

On exit from the while loop program, will continues the execution of the next statement immediately after the while loop.

Syntax:-


1
2
3
4
while(test condition)
{
body of the loop
}

while loop example in c

The below program is to print the value from 1 to 10 using a while loop.

1
2
3
4
5
6
7
8
9
10
11
12
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
while(i<=10)
{
printf("%d\t",i);
i++;
}
getch();
}

Output:

while loop in c

Explanation of the above program in detail:

In the above example of the while loop program using c language,

First I have taken an integer value i and assigned a value 1. So that when while loop will start execution then they have value in i.

Now while loop will begin. At the first time while loop will compare the value of i with then and in comparison it will validate is value of i is smaller or equal to 10 is true or false.

If condition satisfied then the body will execute and print the value of i and increase value of i by 1.

Now next time again while the loop will execute and check the condition, if the condition will satisfy the value will be printed otherwise the loop will be terminated. Like when the value of I become 11 then while condition validation failed and loop terminated.

Let’s see one more example

Below example is to print even number using while loop c programming

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
while(i<=10)
{
if(i%2==0)
{
printf("%d\t",i);
}
i++;
}
getch();
}

Output:

while loop in c programming example

I hope now you have understood while loop