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.while loop in Java?while loopwhile loop repeats code as long as a condition is true, useful when we don't know how many times to repeat.while loop in Java?while (condition) { }.int count = 1;
while (count <= 3) {
System.out.print(count + " ");
count++;
}int i = 0;
while (i < 5) {
System.out.println(i);
}i < 5, but i is never changed inside the loop.i stays 0, the condition is always true, causing an infinite loop.while loop for this?do-while loop, not a while loop.Pass the test and this pattern moves unknown