Home >>C Tutorial >C While loop

C While loop

While loop in C

The While loop in the C language is generally known as a pre-tested loop, depending on a provided Boolean condition while loop allows a part of the code to be executed multiple times. While loop can also be seen as a repeating if statement. The major use of the while loop lies in the case when the number of iterations are not known in advance.

Syntax of the while loop in the C language

Here is the syntax of the while loop in the C language:

 while(condition)
 {  
//code that is to be executed  
}  

Here is the flowchart of the while loop in the C language

Here are couple of examples of the while loop in the C language

1.In the following example, while loop is used to print the table of 1.

#include<stdio.h>  
int main(){    
int i=1;      
while(i<=10){      
printf("%d \n",i);      
i++;      
}  
return 0;  
}    
Output :
1 2 3 4 5 6 7 8 9 10

2. In this following example, while loop is used to print table for any provided number by the user:

#include<stdio.h>  
int main(){    
int i=1,number=0,b=9;    
printf("Please enter a number of your choice: ");    
scanf("%d",&number);    
while(i<=10){    
printf("%d \n",(number*i));    
i++;    
}    
return 0;  
}   
Output :
Please enter a number of your choice: 20
20 40 60 80 100 120 140 160 180 200

Let's have a look at the properties of the while loop

  • In order to check the condition, a conditional expression is used. Until the provided condition is failed, the statements defined within the while loop will execute repeatedly.
  • The condition will turn out to be true if it returns 0 and it will return non-zero number, if the condition is false.
  • The condition expression is mandatory in the while loop.
  • Users can run a while loop without a body.
  • Users can have more than one conditional expression in the while loop.
  • The braces are optional if the loop body contains only one statement.

Here are 3 examples of the while loop to give you a better understanding of the topic: Example 01

#include<stdio.h>  
void main ()  
{  
    int j = 1;  
    while(j+=2,j<=10)  
    {  
        printf("%d ",j);   
    }  
    printf("%d",j);  
}  
Output :
3 5 7 9 11

Example 02

#include<stdio.h>  
void main ()  
{  
    while()  
    {  
        printf("hi Phptpoint");   
    }  
}  
Output :
compile time error: while loop can't be empty

Example 03

#include<stdio.h>  
void main ()  
{  
    int x = 10, y = 2;  
    while(x+y-1)  
    {  
        printf("%d %d",x--,y--);  
    }  
}  
Output :
infinite loop

Infinitive while loop in the C langauge

In the while loop, if the expression passed results in any non-zero value then the loop will run for an infinite number of times.

while(1)
{  
//statement  
}