while loop in c programming



While loop:

It is pre tested loop. It is used when we have to execute a part of code in unknown numbers of times.
Syntax:

while (Expression){
Loop body
}

Properties of while loop:

1. Task of the expression is to check the condition. Loop will execute until condition is true otherwise loop will terminate.  

2. If any expression returns zero then condition will false and if it returns any non- zero number then condition will true. For example:

(a)
#include<stdio.h>
int main(){
    int x=3,y=2;
   
    while(x+y-1){
         printf("%d ",x--+y);
    }
    return 0;    
}
     
Output: 5 4 3 2

(b)
#include<stdio.h>
int main(){
    float a=1.5f;
   
    while(a){
         printf("%.f ",a);
         a-=.5f;
    }
    return 0;     
}
    
Output: 2 1 0

3.  In while loop condition expression is compulsory. For example:

#include<stdio.h>
int main(){
    while(){
         printf("Hello world");
    }
return 0;        
}

Output: Compilation error

4. While loop without any body is possible. For example:

#include<stdio.h>
int main(){
    int i=0;
   
    while(i++,i<=8);
    printf("%d ",i);
    return 0;         
}

Output: 9

5.  In while loop there can be more than one conditional expression. For example

#include<stdio.h>
int main(){
    int x=2,y=2;
    while(x<=5,y<=3)
         printf("%d %d ",++x, ++y);
return 0;        
}

Output: 3 3 4 4

6. If loop body contain only one statement the brace is optional. For example:

#include<stdio.h>
int main(){
    while(!printf("Hello world"));
return 0;        
}

Output: Hello world


For loop
Do while loop
break and continue
Nested loop
C tutorial home.
Post a Comment