C – while loop
Definition
• A loop is used for executing a block of statements
repeatedly until a given condition returns false. In the
previous tutorial we learned for loop. In this guide
we will learn while loop in C.
Syntax of while loop:
while (condition test)
{
//Statements to be executed repeatedly
// Increment (++) or Decrement (--) Operation
}
Flow Diagram of while loop
Example of while loop
#include <stdio.h>
int main()
{
int count=1;
while (count <= 4)
{
printf("%d ", count);
count++;
}
return 0;
}
Guess the output of this while loop
#include <stdio.h>
int main()
{
int var=1;
while (var <=2)
{
printf("%d ", var);
}
}
Examples of infinite while loop
#include <stdio.h>
int main()
{
int var = 6;
while (var >=5)
{
printf("%d", var);
var++;
}
return 0;
}
Example 2
#include <stdio.h>
int main()
{
int var =5;
while (var <=10)
{
printf("%d", var);
var--;
}
return 0;
}
Example of while loop using logical
operator
#include <stdio.h>
int main()
{
int i=1, j=1;
while (i <= 4 || j <= 3)
{
printf("%d %d\n",i, j);
i++;
j++;
}
return 0;
}