Sunday, June 26, 2011

How Use Loops in C-'While' Loops

0 comments


WHILE loops are very simple and the syntax is:
while(condition)
{
Code to execute while the condition is true
}
 The true represent a boolean expression which could be while(x==1) or while(x!=7),x does not equal to 7.It can be any combination of boolean statements that are legal.Even, while(x==5||y==7) which says execute the code while x equal to 5 or y equal to 7.


Example:


To print numbers up to 10:
#include<stdio.h>
int main()
{
int x=0;  /*Don't forget to declare variables*/
while(x<10) /*while x less than 10*/
{
printf("%d",x);
x++; /*Update x so the condition can be met eventually */
}
getchar();
}
This was another example ,but it is longer than FOR loop.The easiest way to think of the loop is that when it reach the brace at the end it jumps back up to the beginning of the loop,which check the condition again and decides whether to repeat the block another time,or stop and move to the next statement after the block.


More example using 'while' loop


<<Prev Home Next>>



Leave a Reply