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.
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
booleancondition holds — useful whenever work must be done again and again. - Main Java loop forms:
for,while,do-while, and enhancedfor(for-each). Nested loops combine them for grids and tables. for/whileare entry-controlled (test first — body may run 0 times).do-whileis exit-controlled (body first — runs at least once).- Unlike C/C++, the loop condition must be
boolean.while (n)for anintdoes not compile — writewhile (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.
- 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).
| Part | Meaning | Real-life mapping |
|---|---|---|
| Initialization | Start the counter | Set day = 1 |
| Condition | Keep going while true | day <= 7 for a week |
| Update | Move toward the end | day++ each morning |
| Body | The repeated action | Show 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.
| Point | while | do-while |
|---|---|---|
| Control type | Entry-controlled | Exit-controlled |
| Condition checked | Before the body | After the body |
| If condition is false at start | Body runs 0 times | Body still runs 1 time |
| Minimum executions | 0 | 1 |
| Semicolon after condition | No | Yes — } while (cond); |
| Typical use | Unknown count; may skip entirely | Must run once (menu, retry, confirm) |
Where do-while is required
- Use
do-whilewhen 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
whileorfor.
| Situation | Why do-while fits | Real-life example |
|---|---|---|
| Menus / dashboards | Show options first, then read choice | ATM / food-court menu |
| Input validation retry | Read once, then re-prompt if invalid | Enter marks until 0–100 |
| Play again / continue? | One round first, then ask to repeat | Quiz rematch |
| Confirm action | Show summary once, then Y/N | Confirm 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 anIterator).- 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.
| Role | Typical name | Real-life meaning |
|---|---|---|
| Outer loop | row / day / i | Moves to the next group |
| Inner loop | col / period / j | Visits every item in that group |
| Inner body | print / compute | One seat, one cell, one star |
| After inner ends | System.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.
| Situation | Best choice | Real-life example |
|---|---|---|
| Known count / indexes | for | Print 1 to 100, table rows |
| Unknown count; may be zero | while | Drain tank while level > 0 |
| Must run at least once | do-while | Menu, validate input, play again |
| Visit every item in a collection | Enhanced for | List all cart items |
| 2D grids / patterns / tables | Nested for | Seats, stars, timetable, matrix |
Advanced — Loops
Entry-controlled vs exit-controlled
forandwhiletest before entry — zero iterations are possible.do-whiletests 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)orfor (;;)— always plan abreak/returnexit.
| Kind | Loops | First action | Min runs |
|---|---|---|---|
| Entry-controlled | while, for | Check condition | 0 |
| Exit-controlled | do-while | Run body | 1 |
break, continue, and labels
breakleaves only the innermost loop or switch.continueskips the rest of the current iteration.- A label (
outer:) letsbreak outer;leave a nested loop — useful, but keep it rare and obvious. - In
for,continuestill runs the update (i++). Inwhile/do-while, you must update yourself beforecontinueor you can infinite-loop. - To stop both levels without a label, use a
booleanflag on the outer condition, or extract a method andreturn.
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
ArrayListwhile using for-each — you getConcurrentModificationException. Use anIterator.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
forwhen you needior reverse order.
Real-life loop models (combined)
- Factory belt:
whileitems remain on the belt, pack them. - TV remote menu:
do-whileuntil the user selects Exit. - School timetable: nested
forover days and periods. - Playlist / cart: enhanced
forover every title or price. - OTP retry:
do-whileuntil the code matches or attempts are exhausted (combine with a counter).
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.
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);
}
} Problem Solving Tricks
- Prefer enhanced
forwhen you do not need the index. - Java loop conditions are boolean-only; never write
while (n)for an int. - In
for,continuestill runsi++. Inwhile, update beforecontinue. - Use a labeled
break(or a methodreturn) to leave nested loops — a plainbreakexits only the inner loop. - The usual array bound is
i < a.length.i <= a.lengththrowsArrayIndexOutOfBoundsException. - Do not remove from an
ArrayListinside for-each; use anIteratoror a classic index loop. - Infinite loops need a clear
breakor they belong in servers (while (running)). - Nested n × n loops are O(n²) — mention that in interviews.
- Do not force
do-whilewhen the body must be skippable; usewhile/for. - Name nested indexes
row/colori/j— never reuse oneifor both levels.
Practice Programs List
- Print 1 to N with a
forloop. - Write a
whilethat sums the digits of an integer. - Write a
do-whilethat prints 1..5 and explain why it still prints when started from 0 in a separate trial. - Sum an array with both classic
forand enhancedfor; confirm the same result. - Print a multiplication table 1–10 with nested
for. - Print a right triangle of stars with nested loops.
- Find the first pair (i, j) with i + j == 10 using a labeled
break. - Count vowels in a
char[]with a loop andcontinueon consonants. - Simulate a 3-option menu with
do-whileuntil Exit. - Reverse-print an array with a classic
forfromlength - 1down to 0 (enhanced for cannot do this). - Show that
while (false) { }compiles but a do-while with a false condition still runs once. - Iterate an
ArrayListand remove even numbers safely with anIterator(not for-each).