While loop in C Programming Language

When we want to execute a set of statements or a block of code repeatedly till a particular condition is true, we use LOOP.

void main(){
int x;

while( x < 10 ) {
   printf("value of x: %d\n", x);

The structure of while loop is a bit different from for loop, Here to start with we use while keyword then in round brackets we mention a termination condition(eg: x<10). As per our example the while loop body code will be executed for values of x=1,2,3,4,5,6,7,8,9 but when x=10 the control will come out of while loop. One more very important element of while loop is increment/decrement(x++/x–) that we mention in while loop body, but if we don’t mention it then our program will go in infinite loop as indicated by the white arrow. Means by using x++/x– we are simply trying to reach closer to the termination condition but if we don’t include it in while loop then we will never be able to reach to the termination condition, Hence resulting in infinite loop. Expected output is indicated by yellow arrow.

Leave a Reply

Your email address will not be published. Required fields are marked *