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.

11 comments:

Anonymous said...

you gave most preference only for pointers. you didn,t give more explanations for other topics. but Still it's super..............

Anonymous said...

what are the differnt types of while loop?give the flow charts for each of them.give one example each and bring out the differnces.?..can any1 ans dis?

Anonymous said...

Hi!
If you write the explanation for the out put in the examples will useful.

Anonymous said...

can you briefly explain question 1

Anonymous said...

I think u should give explanation for output.

Anonymous said...

explain the output of 2(b)

sivaraman p said...

very useful.

Divya Balan said...

#include
int main(){
float a=1.5f;

while(a){
printf("%.f ",a);
a-=.5f;
}
return 0;
}
how the result is getting?plz explain

Annoymos said...

In printf command here we are using %.f instead of %f thats why we r getting 2 1 0..... oderwise if we use %f answer will be 1.5,1,.5

vansh goel said...

6
56
456
3456
23456
123456

vansh goel said...

6
56
456
3456
23456
123456