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
1
2
3
4
2. Key Points of the While Loop
- The condition is checked before each iteration, so the loop may not execute at all if the condition is false initially.
- The loop will execute as long as the condition evaluates to true.
- If the condition becomes false after a few iterations, the loop terminates.
3. When to Use the While Loop
- Use the while loop when you do not know the number of iterations beforehand and want to keep iterating as long as a condition remains true.
- It is particularly useful when the loop needs to check the condition before executing the code block, ensuring the code runs only when the condition is met.
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 |