🎯 What you will learn

Loops are how computers do repetitive work efficiently. A compound interest calculator that would take 100 lines without a loop takes 4 with one. Java has three loop constructs, each with a natural home:

LoopBest forKey feature
forKnown iteration countInit, condition, update in one line
for-eachIterating arrays/collectionsNo index needed, cleaner syntax
whileUnknown count, condition-drivenMay execute 0 times
do-whileMust execute at least onceCondition checked after body
💼 Interview reality: "Write a program to print the Fibonacci series" and "Reverse a number using a loop" are the most common loop questions in campus placements. Both appear in the mini challenge below.

🔁 The for loop

Structure: for (initialisation; condition; update). All three parts are optional (omitting condition gives an infinite loop — useful with break). The loop variable (i, year) is local to the loop block.

javac ForLoop.java && java ForLoop
ForLoop.javaLesson 04 · compound interest table
verified output
Year | Balance -----|---------- 1 | ₹108,000.00 2 | ₹116,640.00 3 | ₹125,971.20 4 | ₹136,048.90 5 | ₹146,932.81

⏳ while and do-while

while: checks the condition before each iteration — may run zero times. Use when you don't know how many iterations will happen (e.g., draining a payment queue until it's empty or funds run out).

do-while: checks the condition after — always runs at least once. Perfect for "show the prompt, then ask again if wrong" patterns like OTP entry.

javac WhileDoWhile.java && java WhileDoWhile
WhileDoWhile.javaLesson 04 · wallet payments + OTP retry
verified output
=== while loop === Paid ₹300 — balance: ₹700.00 Paid ₹250 — balance: ₹450.00 Paid ₹200 — balance: ₹250.00 Insufficient funds — stopped at payment 4 === do-while loop === OTP entered: 1111 — wrong OTP entered: 9999 — wrong OTP entered: 4821 — CORRECT

🛒 Real-world scenario

🛒
Real-world scenario · NaijaCart
Tunde processes a batch of transactions, skipping reversals

Tunde is a backend engineer at NaijaCart in Lagos. The daily settlement job reads an array of transaction amounts. Negative values are reversals (skip them). The sentinel value -9999 marks the end of the day's feed — stop processing there. He uses break and continue to handle both cases cleanly.

javac BreakContinue.java && java BreakContinue
BreakContinue.javaNaijaCart · break and continue
verified output
Processing transactions: + Credited ₹500 → Skipping reversal: ₹-200 + Credited ₹1500 → Skipping reversal: ₹-50 + Credited ₹300 → Sentinel found. Stopping. Processed: 3 txns, Total: ₹2300.00

🧩 Mini challenge

Three loop exercises
Task 1 — Fibonacci series

Print the first 10 Fibonacci numbers using a for loop: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Each number is the sum of the two before it. Use three variables: a, b, temp.

Task 2 — Reverse a number

Given int n = 84521, reverse its digits using a while loop (extract the last digit with % 10, build the reversed number by multiplying by 10 and adding). Print 12548.

Task 3 — EMI schedule

Print a 6-month EMI schedule for a ₹1,00,000 loan at 12% annual rate. Each row: month number, opening balance, interest, EMI (₹1,776.98), closing balance. Use a for loop and printf.

🎤 Interview Q&A

EasyWhat is the difference between break and continue?
+

break exits the loop entirely — execution jumps to the statement after the closing brace. continue skips the rest of the current iteration and jumps to the loop's update expression (for) or condition check (while/do-while). Use break when you have found what you were looking for or hit a sentinel. Use continue to skip invalid or irrelevant entries without exiting the loop.

EasyWhat is the difference between while and do-while?
+

A while loop checks the condition before entering the body — if the condition is false from the start, the body never executes (zero iterations). A do-while executes the body first and checks the condition afterwards — it always runs at least once. Use do-while for input/retry scenarios where you must take the action before you know whether to repeat (e.g., OTP entry, menu display).

MediumHow do you iterate over an array with an index and when do you use for-each instead?
+

Use indexed for (int i = 0; i < arr.length; i++) when you need the index itself — to modify the array in place, access adjacent elements, iterate backwards, or track position. Use enhanced for-each (for (T item : collection)) when you only need each element's value — it's cleaner, avoids off-by-one errors, and works on any Iterable, not just arrays. You cannot modify the array through the for-each loop variable — it's a copy of the reference/value.

MediumWhat causes an infinite loop and how do you avoid it?
+

A loop becomes infinite when its exit condition is never met. Common causes: (1) forgetting to update the loop variable (while (i < 10) without i++); (2) updating the wrong variable; (3) floating-point comparison that never reaches exact equality (while (d != 1.0) — use < instead). To avoid: always trace the update path, add a maximum-iteration guard for safety-critical loops, and prefer for-each when you don't need explicit control.

HardHow do labelled break and continue work in nested loops?
+

Java allows labels on loops: outer: for (...) { inner: for (...) { break outer; } }. break outer exits the outer loop, not just the inner one. continue outer skips the rest of the outer body and moves to the outer loop's next iteration. This is useful in matrix search (stop all loops once the target is found) or multi-dimensional batch processing. Labelled breaks are rare in production code — if you need them often, consider refactoring the nested logic into a method with a regular return.

📝 Quiz — 5 questions

Question 1 of 5
How many times does a do-while loop always execute at minimum?
Question 2 of 5
Which statement skips the current iteration but continues the loop?
Question 3 of 5
What does for (int i = 0; i < 5; i++) produce as final value of i after the loop?
Question 4 of 5
Can you modify an array element through a for-each loop variable?
Question 5 of 5
Which loop is best when you know exactly how many times to iterate?
0
/ 5
Quiz complete!

Next: methods and scope →

⚠️ Common mistakes

Off-by-one error
for (int i = 1; i <= arr.length; i++) causes ArrayIndexOutOfBoundsException on the last iteration — arrays are zero-indexed. Use i < arr.length. This is the #1 array bug in interviews.
Infinite loop from missing update
while (balance > 0) { balance += interest; } — adding to balance instead of subtracting means balance never reaches 0. Always trace the update path before running a while loop.
Modifying collection during for-each
Adding or removing elements from a list inside a for-each loop throws ConcurrentModificationException. Use an explicit iterator with iterator.remove(), or collect items to remove and delete them after the loop.
Using == to compare floats as loop exit
while (d != 0.0) may never exit due to floating-point precision errors. Use while (d > 0.001) with a small epsilon instead of exact equality checks on doubles.

✅ Key takeaways

  • Use for when the iteration count is known; while when driven by a condition; do-while when at least one execution is required.
  • For-each (for (T item : collection)) is cleaner than indexed for when you don't need the index.
  • break exits the entire loop; continue skips only the current iteration.
  • Arrays are zero-indexed — loop condition is i < arr.length, not i <= arr.length.
  • Avoid floating-point equality in loop conditions — use a tolerance or counter instead.
  • Label loops (outer:) for clean multi-level break/continue in nested structures.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

From loops to production Spring Boot

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →