while Statement in C Language



Let us suppose you want to execute a block of statement 5 times. There is one approach using goto statement as shown below.

#include<stdio.h>
#include<conio.h>
void main(){

int i=0;
clrscr();
label1:
i=i+1;
printf("%d This will be repeated 5 times\n", i);
if(i!=5)
goto label1;
printf("End of the program");
getch();
}

Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program

The above mentioned approach solves our purpose. But it is very tedious job to take care of labels. It also decreases the readability of the program. Hence there is another approach to perform the above task very effectively. We will use while loop.

Syntax:

while(condition){
/*block of statement*/
}
Explanation:

Here, while is the keyword which is know to the compiler.
Condition can be any expression
Here, when while is encountered, condition is checked first by the compiler. If the condition is satisfied then the block of statement inside the while loop is executed. After the execution of block of statement, again condition is check. If the conditional expression returns true, the block of statement is executed again. This process is followed till the conditional expression returns false value.

Let us write the above program using while loop.

#include<stdio.h>
#include<conio.h>
void main(){

int i=0;
clrscr();
while(i!=5){
i=i+1;
printf("%d This will be repeated 5 times\n", i);
}
printf("End of the program");
getch();
}

Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program

As you can see, the out of the above program is same as the one with goto statement in it.
We can also see that the readability of the program increases. Using while loop is much easier than using goto statement as we don’t have worry about positioning of labels.

Thus, while loop would keep on getting executed till the condition being test remains true. When the condition becomes false then the control goes to the first statement immediately after the boy of while loop.
The condition being tested can be relational or logical operators.


Responses

0 Respones to "while Statement in C Language"

Post a Comment

 

Total Pageviews

Return to top of page Copyright © 2011 | Kuppam Engineering College Converted into Blogger Template by Mohan Murthy