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, nested loops, break, continue, and labels — with flowcharts and real-life examples.

What are loops?

  • A loop (iteration) repeats a block of statements while a boolean condition holds — useful whenever work must be done again and again.
  • Main Java loop forms: for, while, do-while, and enhanced for (for-each). Nested loops combine them for grids and tables.
  • for / while are entry-controlled (test first — body may run 0 times). do-while is exit-controlled (body first — runs at least once).
  • Unlike C/C++, the loop condition must be boolean. while (n) for an int does not compile — write while (n != 0) if that is what you mean.
  • Use the flowchart image below to see init, condition, body, and update for each form.

Flowcharts: for, while, do-while & enhanced for

Loops repeat Java statements while a boolean condition holds. The diagram below compares for, while, do-while, and enhanced for — notice do-while runs the body before the first check.

Flowcharts of Java for, while, do-while, and enhanced for loops with syntax and System.out examples for each iteration structure.
Java loop flowcharts — for/while test first; do-while always runs at least once
  • for: known count — init, condition, and update in one line.
  • while: entry-controlled — may run zero times.
  • do-while: exit-controlled — body first, required for menus/retries.
  • enhanced for: visit every element in an array or Iterable.

for loop

  • Best when the number of repetitions is known (count, indexes, fixed steps).
  • Parts: for (initialization; condition; update) { body } — all three parts are optional. for (;;) is an infinite loop.
  • Real-life example: Print attendance numbers 1 to 30 for a class register.
  • Real-life example: Lift visits floors 1 through N in order (known floor count).
PartMeaningReal-life mapping
InitializationStart the counterSet day = 1
ConditionKeep going while trueday <= 7 for a week
UpdateMove toward the endday++ each morning
BodyThe repeated actionShow that day’s task
public class ForCount {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " ");
        }
        // Output: 1 2 3 4 5
    }
}

while loop

  • Entry-controlled: checks the condition before the body. If the condition is false at the start, the body never runs.
  • Best when you repeat until a condition becomes false, and the count is not fixed in advance.
  • Real-life example: Keep withdrawing ATM cash while balance >= amount.
  • Real-life example: Keep asking for a password while it is wrong (and attempts remain).
public class WhileWithdraw {
    public static void main(String[] args) {
        int balance = 5000;
        int amount = 1000;
        while (balance >= amount) {
            balance -= amount;
            System.out.println("Withdrawn. Left: " + balance);
        }
    }
}

do-while loop

  • Exit-controlled: runs the body first, then checks the condition. The body runs at least once even if the condition is initially false.
  • Syntax ends with a semicolon: } while (condition);
  • Real-life example: Show a restaurant menu at least once, then ask Order again?
  • Real-life example: Play one round of a game, then ask Play again?
public class DoWhileOnce {
    public static void main(String[] args) {
        int n = 0;
        do {
            System.out.println("body runs once even when n is 0");
            n--;
        } while (n > 0);
    }
}

Differences between while and do-while

  • Both repeat while a condition is true, but they differ in when the condition is checked and the minimum executions.
  • Memorize: while = check then do; do-while = do then check.
Pointwhiledo-while
Control typeEntry-controlledExit-controlled
Condition checkedBefore the bodyAfter the body
If condition is false at startBody runs 0 timesBody still runs 1 time
Minimum executions01
Semicolon after conditionNoYes — } while (cond);
Typical useUnknown count; may skip entirelyMust run once (menu, retry, confirm)

Where do-while is required

  • Use do-while when the body must execute at least once before you can decide whether to repeat.
  • If skipping the body on a false start condition would be wrong, do-while is the natural fit.
  • If the body must not run when the start condition is false (empty queue, n is 0), use while or for.
SituationWhy do-while fitsReal-life example
Menus / dashboardsShow options first, then read choiceATM / food-court menu
Input validation retryRead once, then re-prompt if invalidEnter marks until 0–100
Play again / continue?One round first, then ask to repeatQuiz rematch
Confirm actionShow summary once, then Y/NConfirm delete?
public class CafeMenu {
    public static void main(String[] args) {
        int choice = 0;
        int[] picks = {1, 2, 3};
        int k = 0;
        do {
            System.out.println("1 Tea  2 Coffee  3 Exit");
            choice = picks[k++];
            if (choice == 1) System.out.println("Tea served");
            else if (choice == 2) System.out.println("Coffee served");
        } while (choice != 3);
        System.out.println("Thank you");
    }
}

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<T> (ArrayList, HashSet, …).
  • Real-life example: Print every product price in a cart, or mark attendance for every name in a list.
public class ForEachDemo {
    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 + " ");
        }
    }
}

Nested loops

  • A nested loop is a loop inside another loop. The inner loop finishes all of its iterations for each outer-loop iteration.
  • Most common form: nested for — outer = rows / groups, inner = columns / items in that group.
  • Total inner-body runs is about (outer count) × (inner count) when both run fully.
  • Real-life example: Cinema seats — for each row, visit every seat. School timetable — for each day, print every period.
RoleTypical nameReal-life meaning
Outer looprow / day / iMoves to the next group
Inner loopcol / period / jVisits every item in that group
Inner bodyprint / computeOne seat, one cell, one star
After inner endsSystem.out.println()Start a new line / next group
public class SeatGrid {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 4; col++) {
                System.out.print("R" + row + "C" + col + " ");
            }
            System.out.println();
        }
    }
}

Which loop should you use?

  • Match the loop shape to the problem — readability matters more than cleverness.
SituationBest choiceReal-life example
Known count / indexesforPrint 1 to 100, table rows
Unknown count; may be zerowhileDrain tank while level > 0
Must run at least oncedo-whileMenu, validate input, play again
Visit every item in a collectionEnhanced forList all cart items
2D grids / patterns / tablesNested forSeats, stars, timetable, matrix
L2

Advanced — Loops

Entry-controlled vs exit-controlled

  • for and while test before entry — zero iterations are possible.
  • do-while tests after the body — the right model for act, then decide.
  • You can rewrite do-while as while by duplicating the body once before the loop — that duplication is why do-while exists.
  • Infinite loops: while (true) or for (;;) — always plan a break / return exit.
KindLoopsFirst actionMin runs
Entry-controlledwhile, forCheck condition0
Exit-controlleddo-whileRun body1

break, continue, and labels

  • break leaves only the innermost loop or switch. continue skips the rest of the current iteration.
  • A label (outer:) lets break outer; leave a nested loop — useful, but keep it rare and obvious.
  • In for, continue still runs the update (i++). In while / do-while, you must update yourself before continue or you can infinite-loop.
  • To stop both levels without a label, use a boolean flag on the outer condition, or extract a method and return.
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);
            }
        }
    }
}

Off-by-one, for-each mutation, and complexity

  • The usual 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.remove() or iterate indexes backward.
  • Nested loops over n × n are O(n²). Say this out loud in interviews when you write them.
  • Enhanced for cannot run backward and hides the index — use a classic for when you need i or reverse order.

Real-life loop models (combined)

  • Factory belt: while items remain on the belt, pack them.
  • TV remote menu: do-while until the user selects Exit.
  • School timetable: nested for over days and periods.
  • Playlist / cart: enhanced for over every title or price.
  • OTP retry: do-while until the code matches or attempts are exhausted (combine with a counter).
L3

Tricky Interview Points

Q1) What is a loop in Java?

Answer A control structure that repeats a block while a boolean condition remains true, or for each element in an array or Iterable.

Q2) Difference between while and do-while?

Answer while is entry-controlled: it checks first, so the body may run zero times. do-while is exit-controlled: the body runs first, then the condition is checked, so it runs at least once.

Q3) When is do-while required or clearly preferred?

Answer When the body must execute at least once before repeating — menus, input-validation retries, play again, and any act-then-decide flow.

Q4) Can you write while (1) in Java?

Answer No. The condition must be boolean. Use while (true) or for (;;). while (1) is a C/C++ habit and does not compile.

Q5) for vs while — when to choose which?

Answer Prefer for when initialization, condition, and update are clear (known counts/indexes). Prefer while when the stop condition is event or sentinel based.

Q6) What does the enhanced for loop require?

Answer An array or an Iterable. It hides the index and uses an Iterator under the hood for collections.

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

Answer Use a labeled break (break outer;), extract the loops to a method and return, or set a flag that the outer loop checks.

Q8) Is for(;;) legal?

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

Q9) 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.

Q10) Can a for-each loop run backward?

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

Q11) Difference between break and continue?

Answer break exits the innermost loop immediately. continue skips the rest of the current iteration and proceeds to the next one.

Q12) Does continue skip the for-update?

Answer No. In a for loop, continue still runs the update (i++). In while/do-while you must update yourself before continue.

Q13) What is an off-by-one error in loops?

Answer Using the wrong bound (i < n vs i <= n) so the loop runs one time too many or too few — common with 0-based vs 1-based counting.

Q14) How many times does the inner body run for outer 1..3 and inner 1..4?

Answer 3 × 4 = 12 times, if both loops run fully with no break or continue.

L4

Simple Programs

for — print 1 to N

public class ForOneToN {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            System.out.print(i + " ");
        }
    }
}

while — sum of digits

public class DigitSum {
    public static void main(String[] args) {
        int n = 1234, sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        System.out.println("Sum = " + sum);
    }
}

do-while — ticks then stop

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

Enhanced for — print array

public class ForEachPrint {
    public static void main(String[] args) {
        int[] nums = {2, 4, 6};
        for (int n : nums) {
            System.out.print(n + " ");
        }
    }
}

Nested for — star triangle

public class StarTriangle {
    public static void main(String[] args) {
        int n = 4;
        for (int row = 1; row <= n; row++) {
            for (int star = 1; star <= row; star++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Nested loop and labeled break

public class LabeledBreakDemo {
    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);
            }
        }
    }
}

continue — skip consonants

public class CountVowels {
    public static void main(String[] args) {
        char[] letters = {'j', 'a', 'v', 'a'};
        int vowels = 0;
        for (char c : letters) {
            if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u') {
                continue;
            }
            vowels++;
        }
        System.out.println("vowels = " + vowels);
    }
}
L5

Problem Solving Tricks

  • Prefer enhanced for when you do not need the index.
  • Java loop conditions are boolean-only; never write while (n) for an int.
  • In for, continue still runs i++. In while, update before continue.
  • Use a labeled break (or a method return) to leave nested loops — a plain break exits only the inner loop.
  • The usual array bound is i < a.length. i <= a.length throws ArrayIndexOutOfBoundsException.
  • Do not remove from an ArrayList inside for-each; use an Iterator or a classic index loop.
  • Infinite loops need a clear break or they belong in servers (while (running)).
  • Nested n × n loops are O(n²) — mention that in interviews.
  • Do not force do-while when the body must be skippable; use while / for.
  • Name nested indexes row/col or i/j — never reuse one i for both levels.
L6

Practice Programs List

  1. Print 1 to N with a for loop.
  2. Write a while that sums the digits of an integer.
  3. Write a do-while that prints 1..5 and explain why it still prints when started from 0 in a separate trial.
  4. Sum an array with both classic for and enhanced for; confirm the same result.
  5. Print a multiplication table 1–10 with nested for.
  6. Print a right triangle of stars with nested loops.
  7. Find the first pair (i, j) with i + j == 10 using a labeled break.
  8. Count vowels in a char[] with a loop and continue on consonants.
  9. Simulate a 3-option menu with do-while until Exit.
  10. Reverse-print an array with a classic for from length - 1 down to 0 (enhanced for cannot do this).
  11. Show that while (false) { } compiles but a do-while with a false condition still runs once.
  12. Iterate an ArrayList and remove even numbers safely with an Iterator (not for-each).