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.
Concept 1 of 5
while and do-while
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- init runs once.
- condition is checked before every pass; false ends the loop.
- The body runs.
- update runs, then back to step 2.
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));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
mchanges 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
}* * * * * *
- 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
}| Statement | Effect |
|---|---|
break | Leaves the innermost loop (or switch) immediately. |
continue | Skips the rest of this pass and goes to the next check/update. |
break label | Leaves the loop marked with that label, even from deep inside nested loops. |
continue label | Jumps 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
| Situation | Best loop | Why |
|---|---|---|
| Known number of repetitions (1 to n) | for | Counter, condition and update sit together in one line. |
| Visit every element of an array or list | for-each | No index errors; clearest to read. |
| Repeat until something happens (sentinel, end of input) | while | May run zero times. |
| Ask the user at least once (menu, validation) | do-while | Body runs before the first check. |
| Search a 2-D grid and stop at the first hit | nested for + labeled break | Leaves both loops in one step. |
Worked example 1 of 3
Worked example 1
Hi print? for (int i = 0; i < 10; i += 3) System.out.println("Hi");Show the solution
Worked example 2 of 3
Worked example 2
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 + " ");
}2 3 5 7 11 13 17 19 23 29
Worked example 3 of 3
Worked example 3
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.
Show the answer
int s = 0; for (int i = 2; i <= 100; i += 2) s += i; System.out.println(s); // 2550
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--;
}int i = 10; do { i++; } while (i < 5); System.out.println(i);Show the answer
Practice
Practice (2 of 2)
Try each one on paper first, then check your answer.
11 21 2 3Show the answer
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) System.out.print(j + " ");
System.out.println();
}Show the answer
int count = 0;
while (n > 0) { n /= 10; count++; }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.