A while loop repeats its body as long as a condition stays true. Before each pass it checks the condition; when the condition becomes false, the loop ends and the program continues after it.
int i = 1; while (i <= 3) { System.out.println(i); i++; }
Check 1 <= 3 (print 1), 2 <= 3 (print 2), 3 <= 3 (print 3), then 4 <= 3 is false — stop. Output is 1, 2, 3 on three lines.
1
2
3
▶ Try it: run this, then change 5 to a bigger or smaller number — the loop prints that many lines.
5
How many lines does this print?
int i = 0; while (i < 3) { System.out.println("x"); i++; }
Type exactly what this prints (each number on its own line):
int n = 5; while (n > 0) { System.out.println(n); n--; }
How many times does the body run?
int i = 1; while (i <= 5) { // body i++; }
True or false?
Assemble a while loop that prints hi three times.
hi