THINK FIRST·CODE LATER

← Java Programming
Chapter 7 · Week 7

Loops and Iteration

Before You Start: What You Must Be Able to Do

Before the questions, make sure you can: write the three Java loops from memory and say which one fits a given problem; trace a loop and give the final value of every variable, including the counter; explain why a do loop always executes at least once; use break and continue correctly and predict their effect on a counter; count the total iterations of a nested loop; validate user input with a loop; and recognise, by inspection, the three ways a loop becomes infinite.

The three loops

// 1. while -- test first; may run zero times
int i = 0;
while (i < 5) { System.out.print(i); i++; }

// 2. do...while -- test last; always runs at least once; note the semicolon
int j = 0;
do { System.out.print(j); j++; } while (j < 5);

// 3. for -- initialisation; condition; update, all in one line
for (int k = 0; k < 5; k++) { System.out.print(k); }

The for header is executed in this order: the initialisation once; then the condition; then the body; then the update; then the condition again. A variable declared in the header exists only inside the loop — using k after the loop is a compile-time error.

Use When
for the number of repetitions is known or a counter is central (arrays, tables)
while the repetitions depend on a condition that may be false from the start (sentinel, flag, reading data)
do...while the body must run at least once (menus, “play again?”, input validation)

All three are interchangeable in principle; choosing the natural one is a readability decision that is regularly marked.

Counters, accumulators and the value after the loop

int sum = 0;              // accumulator: initialise BEFORE the loop
int i = 0;                // counter
while (i < 5) { sum = sum + i; i++; }
System.out.print(i + " " + sum);      // 5 10

The counter ends at the first value that fails the test (here 5, not 4), and the sum is 0+1+2+3+4 = 10. Questions on this pattern are almost guaranteed in a quiz.

break and continue

break leaves the loop immediately; continue skips the rest of the body and goes to the next test (in a for, the update still happens). In a while loop, continue placed before the update can produce an infinite loop:

int balance = 10;
while (balance >= 1) {
    if (balance < 9) continue;    // balance is never changed again -> infinite loop
    balance = balance - 9;
}

In nested loops, break leaves only the innermost loop.

Nested loops

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= row; col++) System.out.print("*");
    System.out.println();
}                       // prints *, **, *** on three lines

An outer loop of m passes containing an inner loop of n passes runs the inner body m × n times. When the inner limit depends on the outer counter, count the passes one row at a time.

Input validation

Scanner in = new Scanner(System.in);
int age;
do {
    System.out.print("Age (0-120): ");
    while (!in.hasNextInt()) { in.next(); System.out.print("Numbers only: "); }
    age = in.nextInt();
} while (age < 0 || age > 120);

The pattern is: ask, read, test, repeat while the value is unacceptable. A do loop is the natural choice because at least one question must be asked.

The three ways a loop never ends

  1. The control variable is never updated inside the body.
  2. The update moves the variable away from the terminating condition.
  3. A continue in the wrong place, or a stray semicolon (while (i < 5);) detaches the update from the loop.
Remember
  • do...while ends with a semicolon and runs at least once.
  • A counter ends one step beyond the last successful test.
  • A variable declared in a for header dies with the loop.
  • break exits the innermost loop only; continue skips to the next test.
  • for (int i = 0; i < n; i++) runs exactly n times; i <= n runs n+1 times.
Common Pitfalls
  • for (int i = 0; i < n; i++); — the semicolon makes the body empty.
  • Declaring the accumulator inside the loop, so it resets every pass.
  • Using <= with array.length: the last valid index is length - 1.
  • Changing the loop counter inside the body of a for loop and losing track of it.

Ready? Close the notes and practise.

38 questions. Predict the output before you check — that is the skill the exam measures.