Wednesday, February 4, 2015

while loop in C


while loop in C


The while loop in C language is used to iterate the part of program or statements many times.
In while loop, condition is given before the statement. So it is different from the do while loop. It can execute the statements 0 or more times.

When use while loop in C

The C language while loop should be used if number of iteration is uncertain or unknown.

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 while loop in C language

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

Output

1
2
4
3 5
8
6 7 9
10

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

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

Output

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

Infinitive while loop in C

If you pass 1 as a expression in while loop, it will run infinite number of times.
  1. while(1){  
  2. //statement  
  3. }  

No comments:

Post a Comment