C While Loop

The while loop in C is used to repeat a block of code as long as a specified condition is true. The condition is checked before the loop's body is executed, and if the condition is false initially, the body will not execute at all.

1. While Loop Syntax

The while loop continues to execute the code block as long as the given condition is true. If the condition is false from the beginning, the loop will not run.

Syntax:

                        
while (condition) 
{
    // code to be executed
}
                        
                    

Flowchart of while loop in C

Example:

                        
#include <stdio.h>
int main() 
{
  nt i = 0;
  while (i < 5)
    {
       printf("%d\n", i);
       i++;
    }
  return 0;
}
                        
                    

Output:

0
1
2
3
4

2. Key Points of the While Loop

3. When to Use the While Loop

4. Comparison with Other Loops

Feature For Loop While Loop Do-While Loop
Condition Check At the beginning of each iteration At the beginning of each iteration At the end of each iteration
Minimum Iterations Zero or more Zero or more At least one
Use Case When the number of iterations is known When the number of iterations is unknown, condition checked before each iteration When the block must execute at least once, condition checked after each iteration