Chapter 7: Loops
1. Why Loops? (The Big Idea)
Loops let you repeat a block of code multiple times — either a fixed number of times or until a condition is met.
Real-life analogies:
- for loop: Like counting money note by note (you know exactly how many notes you have).
- while loop: Like waiting for the rain to stop (you keep checking until it’s dry).
- do-while: Like eating one more bite even if you’re full (you do it at least once).
Java has four main loop types:
- for (classic)
- Enhanced for (for-each — super clean for arrays/collections)
- while
- do-while
Plus: break, continue, and labeled statements to control them.
2. The Classic for Loop (Best for Known Number of Iterations)
Syntax:
|
0 1 2 3 4 5 6 7 8 |
for (initialization; condition; update) { // code to repeat } |
Parts explained:
- Initialization → runs once before loop starts (usually declare counter)
- Condition → checked before each iteration (if true → run body)
- Update → runs after each iteration (usually i++)
Example 1: Print numbers 1 to 10 (Classic first loop)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
public class ForLoopDemo { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.println("Number: " + i); } } } |
Output:
|
0 1 2 3 4 5 6 7 8 9 |
Number: 1 Number: 2 ... Number: 10 |
Step-by-step execution:
- i = 1 (init)
- Check i <= 10 → true → print 1
- i++ → i=2
- Check i <= 10 → true → print 2
- … continues until i=11 → condition false → loop ends
Example 2: Sum of first 10 natural numbers
|
0 1 2 3 4 5 6 7 8 9 10 |
int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; // sum = sum + i } System.out.println("Sum = " + sum); // 55 |
Example 3: Reverse countdown (from 10 to 1)
|
0 1 2 3 4 5 6 7 8 9 |
for (int i = 10; i >= 1; i--) { System.out.print(i + " "); } // Output: 10 9 8 7 6 5 4 3 2 1 |
Example 4: Nested for loops — Multiplication Table
|
0 1 2 3 4 5 6 7 8 9 10 11 |
for (int i = 1; i <= 5; i++) { // outer loop: rows for (int j = 1; j <= 5; j++) { // inner loop: columns System.out.print(i * j + "\t"); // \t = tab for alignment } System.out.println(); // new line after each row } |
Output:
|
0 1 2 3 4 5 6 7 8 9 |
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 ... |
3. Enhanced For Loop (for-each) — Super Clean for Arrays/Collections
Syntax:
|
0 1 2 3 4 5 6 7 8 |
for (Type variable : arrayOrCollection) { // use variable } |
- Reads: “For each element in this array/collection, do something.”
- Cannot modify the array elements (only read)
- No index access inside loop (use classic for if you need index)
Example: Print all elements of an array
|
0 1 2 3 4 5 6 7 8 9 10 |
String[] cities = {"Mumbai", "Delhi", "Bangalore", "Chennai", "Kolkata"}; for (String city : cities) { System.out.println("City: " + city); } |
Output:
|
0 1 2 3 4 5 6 7 8 |
City: Mumbai City: Delhi ... |
Example: Sum elements of array
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
int[] marks = {85, 92, 78, 95, 88}; int total = 0; for (int score : marks) { total += score; } System.out.println("Total marks = " + total); // 438 |
4. while Loop (Best when you don’t know exact number of iterations)
Syntax:
|
0 1 2 3 4 5 6 7 8 |
while (condition) { // code to repeat } |
- Checks condition before each iteration
- If condition false at start → loop body never runs
Example: Keep asking for password until correct
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Scanner; public class WhileDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String password = "java2026"; String input; System.out.print("Enter password: "); input = sc.nextLine(); while (!input.equals(password)) { System.out.println("Wrong password! Try again."); System.out.print("Enter password: "); input = sc.nextLine(); } System.out.println("Welcome! Password correct."); sc.close(); } } |
Example: Print numbers until sum reaches 100
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
int sum = 0; int num = 1; while (sum < 100) { sum += num; System.out.println("Added " + num + " → Sum = " + sum); num++; } |
5. do-while Loop (Guaranteed to run at least once)
Syntax:
|
0 1 2 3 4 5 6 7 8 |
do { // code to repeat } while (condition); |
- Runs body first, then checks condition
- Even if condition false at start → body runs once
Example: Menu that keeps showing until user exits
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.Scanner; public class DoWhileDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int choice; do { System.out.println("\n=== Simple Menu ==="); System.out.println("1. Say Hello"); System.out.println("2. Say Namaste"); System.out.println("3. Exit"); System.out.print("Enter choice: "); choice = sc.nextInt(); switch (choice) { case 1: System.out.println("Hello!"); break; case 2: System.out.println("नमस्ते!"); break; case 3: System.out.println("Goodbye!"); break; default: System.out.println("Invalid choice!"); } } while (choice != 3); sc.close(); } } |
6. break and continue — Controlling the Loop Flow
| Keyword | What it does | Where used |
|---|---|---|
| break | Immediately exit the loop (jump out) | Inside any loop |
| continue | Skip rest of current iteration, go to next | Inside any loop |
Example: break — Stop when found
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
for (int i = 1; i <= 20; i++) { if (i == 15) { System.out.println("Found 15! Stopping."); break; } System.out.print(i + " "); } // Output: 1 2 3 ... 14 Found 15! Stopping. |
Example: continue — Skip even numbers
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; // skip printing even numbers } System.out.print(i + " "); } // Output: 1 3 5 7 9 |
7. Labeled Statements (Advanced Control — Rarely Needed)
You can give a label to a loop and use break/continue to control outer loops too.
Syntax:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
outer: for (...) { inner: for (...) { if (...) break outer; // exit both loops if (...) continue outer; // skip to next outer iteration } } |
Example: Find first pair that sums to 100
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
outer: for (int i = 1; i <= 50; i++) { for (int j = 1; j <= 50; j++) { if (i + j == 100) { System.out.println("Found: " + i + " + " + j + " = 100"); break outer; // exit both loops } } } |
Quick Recap Table (Your Cheat Sheet)
| Loop Type | Syntax Highlights | Best For | Runs at least once? |
|---|---|---|---|
| for | for (init; cond; update) | Known number of iterations | No |
| Enhanced for | for (Type var : collection) | Arrays / Collections (read-only) | No |
| while | while (cond) | Unknown iterations (check first) | No |
| do-while | do { … } while (cond); | Must run at least once | Yes |
| break | Exit loop immediately | Early termination | — |
| continue | Skip current iteration | Skip unwanted cases | — |
| Labeled | label: for (…) + break label | Control outer loops in nested cases | — |
Common Mistakes & Fixes
| Mistake | Problem | Fix |
|---|---|---|
| for (int i=0; i<10) (no update) | Infinite loop | Add i++ |
| while (true) without break | Infinite loop | Add condition or break |
| Using continue with return | Confusing | Use break or return instead |
| Forgetting ; after for init | Compile error | for (int i=0; i<10; i++) |
| do-while missing ; after while | Compile error | } while (cond); |
Homework for You (Practice to Master!)
- Basic: Print all odd numbers from 1 to 50 using for and while.
- Medium: Ask user for a number N → print first N Fibonacci numbers (0, 1, 1, 2, 3, 5, …)
- Advanced: Nested loops — print this pattern:
text012345678910***************
- Challenge: Use do-while to keep asking user for a positive number until they enter one > 0.
- Fun: Use labeled break to exit two nested loops when you find a pair (i,j) where i*j == 100.
You’re doing fantastic! Loops are one of the most powerful tools in programming — now your programs can repeat tasks like a pro.
