Skip to main content

Control Flow

Loops

Complete lesson for Loops using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Loops

Section: Control Flow. for, while, do-while, enhanced for, break, continue, and labeled loops.

The three classic loops

  • for — known count or index. while — test first. do-while — body runs at least once, then tests.
  • The condition must be boolean. An infinite loop is for (;;) or while (true).
LoopTest whenBody guaranteed?
for (init; cond; step)Before each iterationNo (if cond is first false)
while (cond)Before each iterationNo
do { } while (cond);After each iterationYes, once

Enhanced for (for-each)

  • for (Type item : arrayOrIterable) visits each element. You get no index and must not structurally modify the collection (except through an Iterator).
  • Works on arrays and anything implementing Iterable (ArrayList, HashSet, …).
public class LoopBasics {
    public static void main(String[] args) {
        int[] nums = {2, 4, 6};
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }
        System.out.println();
        for (int n : nums) {
            System.out.print(n + " ");
        }
    }
}

break, continue, labels

  • break leaves the innermost loop or switch. continue skips to the next iteration.
  • A label (outer:) lets break outer; leave a nested loop — useful, but keep it rare and obvious.
L2

Advanced — Loops

Off-by-one, mutation, and complexity

  • The usual for-array pattern is i = 0; i < a.length; i++. Using <= is the classic off-by-one / ArrayIndexOutOfBoundsException.
  • Do not remove from an ArrayList while using for-each — you get ConcurrentModificationException. Use an Iterator or iterate indexes backward.
  • Nested loops over n×n are O(n²). Say this out loud in interviews when you write them.
L3

Tricky Interview Points

Q1) Difference between while and do-while?

Answer while tests first and may run zero times. do-while runs the body once, then tests.

Q2) What does the enhanced for loop require?

Answer An array or an Iterable. It hides the index and the Iterator.

Q3) How do you break out of two nested loops?

Answer Use a labeled break, or extract the loops to a method and return, or set a flag.

Q4) Is for(;;) legal?

Answer Yes. All three for-clauses are optional. for(;;) is an infinite loop.

Q5) Why is modifying a collection in for-each unsafe?

Answer The enhanced for uses an Iterator. Structural changes confuse fail-fast iterators and throw ConcurrentModificationException.

Q6) Can a for-each loop run backward?

Answer Not directly. Use a classic index loop from length-1 down to 0, or a ListIterator.

L4

Simple Programs

Nested loop and labeled break

public class LabeledBreak {
    public static void main(String[] args) {
        outer:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (i * j == 4) {
                    System.out.println("stop at " + i + "," + j);
                    break outer;
                }
                System.out.println(i + " x " + j);
            }
        }
    }
}

do-while input-style loop

public class DoWhileDemo {
    public static void main(String[] args) {
        int n = 3;
        do {
            System.out.println("tick " + n);
            n--;
        } while (n > 0);
    }
}
L5

Problem Solving Tricks

  • Prefer for-each when you do not need the index.
  • Cache list.size() only if you are sure the list does not change; for ArrayList size() is O(1) anyway.
  • Infinite loops need a clear break or they belong in servers (while (running)).
  • Use IntStream.range only when streams make the code clearer — classic for is fine.
L6

Practice Programs List

  1. Print a multiplication table 1–10 with nested for.
  2. Sum an array with both classic for and for-each; confirm the same result.
  3. Write a do-while that prints 1..5.
  4. Find the first pair (i, j) with i + j == 10 using a labeled break.
  5. Count vowels in a char[] with a loop and continue on consonants.