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:

  1. for (classic)
  2. Enhanced for (for-each — super clean for arrays/collections)
  3. while
  4. do-while

Plus: break, continue, and labeled statements to control them.

2. The Classic for Loop (Best for Known Number of Iterations)

Syntax:

Java

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)

Java

Output:

text

Step-by-step execution:

  1. i = 1 (init)
  2. Check i <= 10 → true → print 1
  3. i++ → i=2
  4. Check i <= 10 → true → print 2
  5. … continues until i=11 → condition false → loop ends

Example 2: Sum of first 10 natural numbers

Java

Example 3: Reverse countdown (from 10 to 1)

Java

Example 4: Nested for loops — Multiplication Table

Java

Output:

text

3. Enhanced For Loop (for-each) — Super Clean for Arrays/Collections

Syntax:

Java
  • 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

Java

Output:

text

Example: Sum elements of array

Java

4. while Loop (Best when you don’t know exact number of iterations)

Syntax:

Java
  • Checks condition before each iteration
  • If condition false at start → loop body never runs

Example: Keep asking for password until correct

Java

Example: Print numbers until sum reaches 100

Java

5. do-while Loop (Guaranteed to run at least once)

Syntax:

Java
  • Runs body first, then checks condition
  • Even if condition false at start → body runs once

Example: Menu that keeps showing until user exits

Java

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

Java

Example: continue — Skip even numbers

Java

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:

Java

Example: Find first pair that sums to 100

Java

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!)

  1. Basic: Print all odd numbers from 1 to 50 using for and while.
  2. Medium: Ask user for a number N → print first N Fibonacci numbers (0, 1, 1, 2, 3, 5, …)
  3. Advanced: Nested loops — print this pattern:
    text
  4. Challenge: Use do-while to keep asking user for a positive number until they enter one > 0.
  5. 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.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *