Home
2Iterative Statements
2

Topic 2 of 13 · Lecture 2

Iterative Statements

Repeating work with while, do-while, for and for-each loops, nesting loops, and controlling them with break, labeled break and continue.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

How would you print the multiplication table from 1 × 1 to 12 × 12 without writing 144 println lines?

A loop lets the computer repeat a block of code while a condition stays true. With one loop inside another, those 144 lines shrink to about five.

In this topic you will learn the four loop forms in Java, when each is the right choice, and how to leave or skip part of a loop early.

Outline · Lecture 2

Topics in this chapter

Select a topic to jump to the slide that explains it.

  1. while loop
  2. do-while loop
  3. for loop
  4. for-each loop
  5. Nested loops
  6. break, labeled break and continue
  7. Choosing the right loop

Concept 1 of 5

while and do-while

while checks first, so its body may run zero times; do-while always runs its body at least once.

while and do-while

int n = 1;
while (n <= 3) {           // check, then run
    System.out.println(n);
    n++;
}

int choice;
do {                       // run, then check
    choice = readMenu();
} while (choice != 0);     // note the semicolon
  • Use while when you might not need to run at all (reading until end of input).
  • Use do-while for menus and input validation: ask at least once.
  • Forgetting n++ gives an infinite loop.

Concept 2 of 5

The for loop

//   init       condition   update
for (int i = 1; i <= 5;     i++) {
    System.out.print(i + " ");
}
// 1 2 3 4 5

for (int i = 10; i > 0; i -= 3)
    System.out.print(i + " ");
// 10 7 4 1
  1. init runs once.
  2. condition is checked before every pass; false ends the loop.
  3. The body runs.
  4. update runs, then back to step 2.
Scope: The variable i declared in the for header exists only inside the loop.

Step through the code

Trace: summing 1 to n

Watch i and sum change on every pass, and see the exact moment the condition becomes false.

Step through the code

Trace: summing 1 to n (cont.)

Step through the code

Trace: digits of a number

A classic while loop: % 10 takes the last digit, / 10 removes it. We add the digits and build the reverse at the same time.

Step through the code

Trace: digits of a number (cont.)

Interactive

Loop explorer

Code example

The enhanced for (for-each) loop

int[] marks = {78, 91, 64, 85};
int total = 0;
for (int m : marks) {          // "for each m in marks"
    total += m;
}
System.out.println("Total: " + total);

String[] names = {"Ayesha", "Rahim", "Nabila"};
for (String s : names)
    System.out.print(s.charAt(0));
Output
Total: 318
ARN
  • Reads every element in order, with no index variable to get wrong.
  • Use a normal for loop when you need the index, want to go backwards, or must change the array: assigning to m changes only the copy.

Concept 3 of 5

Nested loops

for (int i = 1; i <= 3; i++) {          // rows
    for (int j = 1; j <= i; j++) {      // columns
        System.out.print("* ");
    }
    System.out.println();               // next row
}
Output
*
* *
* * *
  • The inner loop runs completely for every single pass of the outer loop.
  • Total work = outer passes × inner passes: a 12 × 12 table does 144 inner steps.
  • Pattern trick: the outer loop picks the row, the inner loop decides how many items that row has — often depending on i.

Interactive

Nested-loop pattern printer

Concept 4 of 5

break, continue and labeled break

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue;   // skip evens
    if (i > 7) break;           // leave the loop
    System.out.print(i + " ");
}
// 1 3 5 7

search:
for (int r = 0; r < 3; r++)
    for (int c = 0; c < 3; c++)
        if (grid[r][c] == target) {
            System.out.println(r + "," + c);
            break search;       // exits BOTH loops
        }
StatementEffect
breakLeaves the innermost loop (or switch) immediately.
continueSkips the rest of this pass and goes to the next check/update.
break labelLeaves the loop marked with that label, even from deep inside nested loops.
continue labelJumps to the next pass of the labeled outer loop.

Step through the code

Trace: continue and labeled break

Follow the two loop counters. continue skips j = 2; break outer ends everything as soon as i × j reaches 6.

Step through the code

Trace: continue and labeled break (cont.)

Concept 5 of 5

Choosing the right loop

SituationBest loopWhy
Known number of repetitions (1 to n)forCounter, condition and update sit together in one line.
Visit every element of an array or listfor-eachNo index errors; clearest to read.
Repeat until something happens (sentinel, end of input)whileMay run zero times.
Ask the user at least once (menu, validation)do-whileBody runs before the first check.
Search a 2-D grid and stop at the first hitnested for + labeled breakLeaves both loops in one step.

Worked example 1 of 3

Worked example 1

How many times does Hi print? for (int i = 0; i < 10; i += 3) System.out.println("Hi");
Show the solution
i takes the values 0, 3, 6, 9 → 4 times. At i = 12 the condition is false.

Worked example 2 of 3

Worked example 2

Print all prime numbers from 2 to 30 using nested loops and continue with a label.
Show the solution
outer:
for (int n = 2; n <= 30; n++) {
    for (int d = 2; d * d <= n; d++)
        if (n % d == 0) continue outer;   // not prime
    System.out.print(n + " ");
}
Output
2 3 5 7 11 13 17 19 23 29

Worked example 3 of 3

Worked example 3

Keep asking for a PIN until the user types 1234, allowing at most 3 tries.
Show the solution
int tries = 0, pin;
do {
    System.out.print("PIN: ");
    pin = in.nextInt();
    tries++;
} while (pin != 1234 && tries < 3);
System.out.println(pin == 1234 ? "Welcome" : "Card blocked");

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. Write a loop that prints the sum of the even numbers from 1 to 100.
Show the answer
int s = 0;
for (int i = 2; i <= 100; i += 2) s += i;
System.out.println(s);   // 2550
2. Rewrite for (int i = 5; i > 0; i--) System.out.print(i); as a while loop.
Show the answer
int i = 5;
while (i > 0) {
    System.out.print(i);
    i--;
}
3. What is the output? int i = 10; do { i++; } while (i < 5); System.out.println(i);
Show the answer
11 — the body runs once before the condition is checked.

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. Print this pattern with nested loops:
1
1 2
1 2 3
Show the answer
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) System.out.print(j + " ");
    System.out.println();
}
5. Count the digits of a positive integer n using a while loop.
Show the answer
int count = 0;
while (n > 0) { n /= 10; count++; }
6. What is the difference between break and continue inside a nested loop?
Show the answer
break leaves the innermost loop entirely; continue skips to its next pass. Neither affects the outer loop unless you use a label.

Check yourself

Quiz

Summary

Summary

  • while checks before the body (0 or more runs); do-while checks after (1 or more runs).
  • for keeps init, condition and update in one line — ideal for counting.
  • for-each visits every element without an index, but cannot change primitive elements.
  • Nested loops: the inner loop completes for every outer pass (work = outer × inner).
  • break leaves a loop, continue skips a pass; labels let both act on an outer loop.