Concept Flow - Why while loop is needed
Start
Check condition
Yes
Execute loop body
Repeat check condition
No
Exit loop
The while loop keeps running its code as long as the condition is true, checking before each run.
int count = 1; while (count <= 3) { System.out.println(count); count++; }
| Step | count | Condition (count <= 3) | Action | Output |
|---|---|---|---|---|
| 1 | 1 | true | Print 1, count = 2 | 1 |
| 2 | 2 | true | Print 2, count = 3 | 2 |
| 3 | 3 | true | Print 3, count = 4 | 3 |
| 4 | 4 | false | Exit loop |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| count | 1 | 2 | 3 | 4 | 4 |
while loop syntax:
while (condition) {
// code to repeat
}
Runs code repeatedly while condition is true.
Checks condition before each run.
Useful when number of repeats is unknown beforehand.