R
Rishtaara
Java Fundamentals
Lesson 8 of 36Article14 min

For Loop & Break/Continue

for (init; condition; update) { ... } is best when you know how many times to repeat.

For — counted loops

for (init; condition; update) { ... } is best when you know how many times to repeat.

Common pattern: for (int i = 0; i < 10; i++) loops 10 times with i from 0 to 9.

Real-life example: For loop is like counting laps on a track — start at 0, run while under 10, add 1 each lap.

For loop
for (int i = 0; i < 5; i++) {
    System.out.println("Lap " + i);
}

// Sum 1 to 10
int sum = 0;
for (int n = 1; n <= 10; n++) {
    sum += n;
}
System.out.println(sum); // 55

Break & Continue — control the loop

break exits the loop immediately. continue skips the rest of this iteration and goes to the next one.

Use break to stop early when you find what you need. Use continue to skip unwanted items.

Real-life example: Searching a bag for keys — break when found. Skipping rotten apples in a basket — continue to next apple.

Break and continue
for (int i = 0; i < 10; i++) {
    if (i == 3) continue; // skip 3
    if (i == 7) break;    // stop at 7
    System.out.println(i);
}
// Prints 0, 1, 2, 4, 5, 6