While loop in c

In my previous article, we have discussed the loop statements in C so we will not discuss what is a loop and all. For that, please visit my last article. Here we will discuss While loop in C.

While Loop in C

  • While loop also executes the statements n number of times until the condition is true.
  • When the condition becomes false, the control passes to the immediate statement/expression of the program.
  • It is an entry-controlled loop.
  • Condition is checked before processing a loop body.
  • Loop body can contain more than one statement.
  • Loop body is always contaned in the curly braces. However If it contains only one statement, then the curly braces are not compulsory.
  • Although, It is a good practice though to use the curly braces even we have a single statement in the body.

Syntax of While Loop in C

while (condition)
{
   statements;
}

Flow Diagram

while loop in c flow chart

From the flow chart above, it’s clear that that loop body will only execute if the condition is true.

In case, if the condition is false, the loop will not execute even once and the loop body will be skipped.

Example

#include <stdio.h>
 
int main ()
{

   int n = 10;

   /* while loop */
   while( n < 20 ) {
      printf("value of n: %d\n", n);
      n++;
   }
 
   return 0;
}

Output

value of n: 10
value of n: 11
value of n: 12
value of n: 13
value of n: 14
value of n: 15
value of n: 16
value of n: 17
value of n: 18
value of n: 19

Explanation

  • The initial value of variable n is 10. This value is checked in condition and as 10 < 20, so the value 10 is printed.
  • Due to increment operator used with variable n (n++), the value will be changed to 11 and checked with the condition again. As 11 < 20, 11 will be printed and the loop will go on.
  • Finally, when value will be incresed to 20 after printing 19, the condition will be checked again and it will become false as 20 is not less than 20.

Infinite while loop in C

If the condition/expression passed in while loop never becomes false, then the loop will run an infinite number of times.

Example 

#include<stdio.h>  
void main ()  
{  
    int x = 10, y = 2;  
    while(x+y-1)  
    {  
        printf("%d %d",x--,y--);  
    }  
}  

Explanation

When the above code will execute, the expression never becomes zero and the loop will go on.

It will be executed an infinite number of times.

We will cover a lot of programming examples in our upcoming articles and execute the programs to see the output with different values.

You Might Like:

1 thought on “While loop in c”

Leave a Comment

Ads Blocker Image Powered by Code Help Pro
Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Please Reload After Disabling Ad\'s