While Loop

while loop in C

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.

Syntax of while loop in C language

The syntax of while loop in c language is given below:
  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart of while loop in C

flowchart of c while loop

Example of the while loop in C language

Let's see the simple program of while loop that prints table of 1.
#include<stdio.h>  
  1. int main(){    
  2. int i=1;      
  3. while(i<=10){      
  4. printf("%d \n",i);      
  5. i++;      
  6. }  
  7. return 0;  
  8. }    

Output

1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using while loop in C

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

Output

Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000

Properties of while loop

  • A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.
  • The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.
  • In while loop, the condition expression is compulsory.
  • Running a while loop without a body is possible.
  • We can have more than one conditional expression in while loop.
  • If the loop body contains only one statement, then the braces are optional.

Example 1

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

Output

3 5 7 9 11

Example 2

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     while()  
  5.     {  
  6.         printf("hello DEVIL");   
  7.     }  
  8. }  

Output

compile time error: while loop can't be empty 

Example 3

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int x = 10, y = 2;  
  5.     while(x+y-1)  
  6.     {  
  7.         printf("%d %d",x--,y--);  
  8.     }  
  9. }  

Output

infinite loop 

Infinitive while loop in C

If the expression passed in while loop results in any non-zero value then the loop will run the infinite number of times.
  1. while(1){  
  2. //statement  
  3. printf("hello DEVIL");
  4. //prints hello DEVIL infinite Times
  5. }  

Comments

Popular posts from this blog

Features of C Language

Flow of C program

Types of LOOPS