java-foundations Lesson 4 20 min read

Loops

Repetition without repetition — for, while, and do-while

Reading: Reges & Stepp: Ch. 5

After this lesson, you will be able to:

  • Write for loops for counted repetition and while loops for conditional repetition
  • Trace through loop execution step by step (the master debugging skill)
  • Choose the right loop type for a given problem
  • Avoid infinite loops, off-by-one errors, and fence-post problems

Why Loops?

Without loops, printing numbers 1 through 1000 would take 1000 println statements. With a loop, it takes three lines:

for (int i = 1; i <= 1000; i++) {
    System.out.println(i);
}

Loops let you execute a block of code repeatedly — either a fixed number of times or until some condition changes.


The for Loop

Use for when you know how many times to repeat:

for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}

The three parts inside the parentheses:

Part Purpose Example
int i = 0 Initialize — runs once before the loop Start counting at 0
i < 5 Test — checked before each iteration Keep going while true
i++ Update — runs after each iteration Move to next count

From CSCD 110: Python’s for i in range(5) does the same thing. Java’s for loop makes the initialization, test, and update explicit rather than hiding them inside range().

Check Your Understanding
How many times does this loop print? for (int i = 1; i <= 10; i++) { System.out.println(i); }
A 9 times
B 10 times
C 11 times
D It depends on the value of i
Answer: B. The loop starts at i = 1 and runs while i <= 10. So it executes for i = 1, 2, 3, ..., 10 — that's 10 iterations. When i becomes 11, the test 11 <= 10 is false and the loop stops.

The while Loop

Use while when you don’t know how many times to repeat — you repeat until a condition becomes false:

Scanner console = new Scanner(System.in);
System.out.print("Enter a positive number: ");
int num = console.nextInt();

while (num <= 0) {
    System.out.print("That's not positive. Try again: ");
    num = console.nextInt();
}
System.out.println("You entered: " + num);

This is input validation — one of the most common uses of while. The loop runs zero or more times depending on what the user enters.


The do-while Loop

A do-while loop runs the body at least once, then checks the condition:

int choice;
do {
    System.out.println("1. Play  2. Quit");
    System.out.print("Choice: ");
    choice = console.nextInt();
} while (choice != 1 && choice != 2);

Use do-while when you need the body to execute before you can check the condition (like showing a menu before reading a choice).


Loop Tracing: The Master Skill

The single most important debugging technique for loops is tracing — stepping through each iteration and tracking variable values:

int sum = 0;
for (int i = 1; i <= 4; i++) {
    sum = sum + i;
}
Iteration i sum before sum after
1 1 0 1
2 2 1 3
3 3 3 6
4 4 6 10

After the loop, sum is 10 (which is 1+2+3+4). If your loop produces unexpected output, trace it on paper.

Check Your Understanding
What is the value of result after this loop? int result = 1; for (int i = 0; i < 3; i++) { result = result * 2; }
A 6
B 8
C 3
D 16
Answer: B. Trace it: result starts at 1. After i=0: result = 1*2 = 2. After i=1: result = 2*2 = 4. After i=2: result = 4*2 = 8. The loop runs 3 times (i = 0, 1, 2), doubling each time: 1 → 2 → 4 → 8.

Choosing the Right Loop

Situation Best Loop Why
“Print 1 to N” for Known count
“Read until sentinel” while Unknown count
“Show menu, then validate” do-while Must run once first
“Process each element” for or enhanced for Index-based or collection
Check Your Understanding

You need to keep asking the user for a password until they enter the correct one. Which loop type is the best choice?


Common Mistakes

Infinite loop — forgetting to update the loop variable:

int i = 0;
while (i < 10) {
    System.out.println(i);
    // Forgot i++! This runs forever.
}

Off-by-one< vs <=:

for (int i = 0; i < 5; i++)   // 0,1,2,3,4 → 5 iterations
for (int i = 0; i <= 5; i++)  // 0,1,2,3,4,5 → 6 iterations
for (int i = 1; i <= 5; i++)  // 1,2,3,4,5 → 5 iterations

When in doubt, trace the first and last iterations.


Summary

for loops handle counted repetition. while loops handle conditional repetition. do-while guarantees at least one execution. Tracing — writing out variable values for each iteration — is the most reliable way to debug loop logic.