β Javaπ
Day 7
Loops in Java
for, while, do-while and enhanced for-each loops with break and continue.
π―
Learning objectives
- βChoose the right loop for the job
- βUse break and continue to control flow
- βIterate arrays cleanly with for-each
π‘ Key points
- for: known number of iterations. while: condition-driven. do-while: runs at least once.
- for-each (enhanced for) is the cleanest way to walk arrays and collections.
- break exits the loop entirely; continue skips to the next iteration.
- Infinite loop: for (;;) or while (true) β must have an internal break.
π» Code examples(5)
#1for loop
javafor (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
Output
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
Three parts: init, condition, update. Runs while condition is true.
#2while loop
javaint n = 10;
while (n > 0) {
System.out.println(n);
n--;
}
Condition checked before every iteration. Zero runs if false initially.
#3do-while
javaint input;
do {
input = readInput(); // pretend method
} while (input < 0);
Body runs at least once β condition checked at the end. Great for input validation.
#4for-each on array
javaint[] marks = {85, 90, 78, 92};
int total = 0;
for (int m : marks) {
total += m;
}
System.out.println(total);
Output
345
Read as 'for each m in marks'. No index needed. Cannot modify array via m.
#5break and continue
javafor (int i = 1; i <= 10; i++) {
if (i == 5) break; // exit loop when i = 5
if (i % 2 == 0) continue; // skip evens
System.out.println(i);
}
Output
1 3
break: leave loop. continue: skip rest of body, go to next iteration.
π― Practice
Q1. Difference between while and do-while?+
while checks the condition first β body may run 0 times. do-while checks after β body runs at least once.
Q2. Print numbers 1-100 skipping multiples of 3.+
for (int i = 1; i <= 100; i++) { if (i % 3 == 0) continue; System.out.println(i); }
Q3. Write an infinite loop that prints 'hi' until user break.+
while (true) { System.out.println("hi"); if (shouldStop()) break; }
π Notes
Nested loops
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}
Outputs a multiplication grid. Time complexity = O(rows Γ cols).
Labelled break
Rare but useful β break out of both loops at once:
outer:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (grid[i][j] == target) break outer;
}
}