What is a while Loop?
A while loop is used to repeat a block of code as long as a condition is true.
Use a while loop when:
- You do NOT know in advance how many times the loop will run
- The loop depends on a condition
Definition
A while loop checks the condition first, and if it is true, the loop body executes.Syntax of while Loop
while(condition) {
// statements
}Important Points
- Condition is checked before execution
- Loop may execute zero times
- It is an entry-controlled loop
Working of while Loop
Step-by-Step Flow:
- Initialize variable
- Check condition
- If condition is true → execute loop body
- Update variable
- Go back to condition
- If condition is false → loop stops
Simple Example: Print 1 to 5
c
1
2#include <stdio.h>
3
4int main() {
5 int i = 1; // initialization
6
7 while(i <= 5) { // condition
8 printf("%d\n", i);
9 i++; // increment
10 }
11
12 return 0;
13}Output:
1
2
3
4
5