Loops: while, for, do-while, break/continue, nested loops
The three loop types, counting iterations, break and continue, extracting digits and star patterns. The topic worth the most points on the midterm: finding output with a trace table and writing methods with loops.
Loops repeat a group of statements over and over. The biggest share of the midterm points is here: “what does this loop print?” questions and “write a method that computes this using a loop” questions. The key to both is the same: run the code on paper, iteration by iteration.
Golden rules:
- At the start of each iteration write the condition: T or F? The moment it is F, the loop ends.
- The value of the counter after the loop is one step ahead: when
i <= 5finishes, i = 6. - do-while runs at least once, while may not run at all.
- break ends the loop, continue only skips that iteration.
- In a nested loop the inner loop runs from start to end on every iteration of the outer one.
The while loop
int i = 1;
while (i <= 5) {
System.out.print(i + " ");
i++;
}
System.out.println();
System.out.println("i after = " + i);
1 2 3 4 5
i after = 6
while checks the condition before every iteration. If the condition is true the body runs, then it goes back to the condition. There must be something in the body that changes the condition (i++); otherwise the condition stays true forever and you get an infinite loop.
Solving with a trace table
In the exam, open a column for each variable and write the condition in a separate column:
int a = 1, b = 0;
while (a < 20) {
b = b + a;
a = a * 3;
}
System.out.println("a=" + a + " b=" + b);
round a < 20 ? b = b + a a = a * 3
start 0 1
1 1 < 20 T 1 3
2 3 < 20 T 4 9
3 9 < 20 T 13 27
4 27 < 20 F → exit
a=27 b=13
When to use while? When you do not know in advance how many iterations it will run: until the digits run out, until the user enters the right password, until a sentinel value (for example -1) arrives (sentinel-controlled).
The for loop
When the number of iterations is known (counter-controlled), for is neater:
for (init; condition; update) {
body
}
Order of execution: init (once) → condition → body → update → condition → body → update → … → condition false → exit.
int sum = 0;
for (int k = 1; k <= 5; k++) sum += k;
System.out.println(sum);
for (int k = 10; k > 0; k -= 3) System.out.print(k + " ");
System.out.println();
for (int k = 0; k < 10; k += 4) System.out.print(k + " ");
15
10 7 4 1
0 4 8
Iteration count and off-by-one
int c1 = 0, c2 = 0, c3 = 0;
for (int k = 0; k < 5; k++) c1++;
for (int k = 1; k <= 5; k++) c2++;
for (int k = 0; k <= 5; k++) c3++;
System.out.println(c1 + " " + c2 + " " + c3);
5 5 6
Running one iteration too few or too many is called an off-by-one error. The rule: if it ends with < the last value is not included, if it ends with <= it is included. In the exam always check the first and the last iteration separately.
PITFALL · the lifetime of the loop variable. The i declared in the header
for (int i = 0; ...)lives only inside the loop. If you writeSystem.out.println(i);after the loop you get acannot find symbolerror. If you need the value later, declare i before the loop.
The do-while loop
int z = 100;
do {
System.out.println("runs once");
} while (z < 0);
int x = 10;
do {
System.out.print(x + " ");
x -= 4;
} while (x > 0);
System.out.println("end " + x);
runs once
10 6 2 end -2
Because the condition is checked at the end, the body runs at least once. It is ideal for showing a menu or for asking again until the user gives a valid value. There is a ; after the final while (...) line; do not forget it.
| Loop | When is the condition checked? | Minimum iterations | Typical use |
|---|---|---|---|
while | at the start | 0 | the end point is unknown |
for | at the start | 0 | the number of iterations is known |
do-while | at the end | 1 | menus, input validation |
break and continue
for (int k = 1; k <= 5; k++) { if (k == 3) continue; System.out.print(k + " "); }
System.out.println();
for (int k = 1; k <= 5; k++) { if (k == 3) break; System.out.print(k + " "); }
System.out.println();
int w = 0;
while (w < 5) {
w++;
if (w % 2 == 0) continue;
System.out.print(w + " ");
}
1 2 4 5
1 2
1 3 5
- break: leaves the loop it is in immediately. The lines below it and the remaining iterations do not run.
- continue: skips the rest of this iteration and moves on to the next one. In a for, the update (
k++) is done first, then the condition is checked.
PITFALL · continue inside a while. In a while, if the update is written after the continue, it never runs and you get an infinite loop. In the example above
w++is at the very start, so it is safe.
The digit extraction pattern
% 10 gives the last digit, / 10 removes the last digit. Digit sum, digit count and reversal are written with the same skeleton:
int n = 4823, ds = 0, dc = 0;
while (n > 0) {
ds += n % 10; // add the last digit
dc++; // count a digit
n /= 10; // drop the last digit
}
System.out.println(ds + " " + dc);
int num = 1234, rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
System.out.println(rev);
17 4
4321
Nested loops and patterns
The outer loop manages the rows, the inner loop manages the characters in that row. The inner loop runs completely from start to end on every iteration of the outer one. When the inner loop finishes, System.out.println() moves to the next line; this line must be outside the inner loop and inside the outer loop.
for (int r = 1; r <= 3; r++) {
for (int col = 1; col <= 4; col++) System.out.print("*");
System.out.println();
}
for (int r = 1; r <= 2; r++)
for (int col = 1; col <= 3; col++)
System.out.print(r + "" + col + " ");
****
****
****
11 12 13 21 22 23
If the inner loop runs a fixed number of times, total iterations = outer × inner (2 × 3 = 6). If the bound of the inner loop depends on the outer variable, count each outer iteration separately and add them up.
Pattern formulas
i is the row number (starting from 1), n is the total number of rows:
| Pattern | Spaces | Stars |
|---|---|---|
| Left triangle | 0 | i |
| Inverted triangle | 0 | n - i + 1 |
| Right-aligned triangle | n - i | i |
| Pyramid | n - i | 2 * i - 1 |
int rows = 4;
for (int r = 1; r <= rows; r++) { // left triangle
for (int j = 1; j <= r; j++) System.out.print("*");
System.out.println();
}
for (int r = 1; r <= rows; r++) { // right-aligned
for (int s = 1; s <= rows - r; s++) System.out.print(" ");
for (int j = 1; j <= r; j++) System.out.print("*");
System.out.println();
}
for (int r = 1; r <= rows; r++) { // pyramid
for (int s = 1; s <= rows - r; s++) System.out.print(" ");
for (int j = 1; j <= 2 * r - 1; j++) System.out.print("*");
System.out.println();
}
*
**
***
****
*
**
***
****
*
***
*****
*******
In a pattern question, first build a table: write the number of spaces and stars for each row, find the relationship with i, then turn it into loop bounds.
Common mistakes
| Wrong idea | The truth |
|---|---|
for (i = 0; i <= 5; i++) is 5 iterations | 6 iterations; <= includes the last value |
After the loop i is the last value used | One step further: the value that broke the condition |
| do-while never runs if the condition is false | It runs at least once |
| continue ends the loop | It only skips that iteration |
| A break in the inner loop also ends the outer loop | Only the inner loop |
for (...); then { } is the loop body | The ; is the body, the block runs once |
| println goes inside the inner loop | Inside the outer loop, after the inner loop |
| In nested loops iterations = outer × inner always | If the inner bound depends on the outer, count iteration by iteration |
Forgetting i++ in a while is no problem | Infinite loop |
Test yourself
Exam-style questions. Solve them on paper first, then reveal the answer.
What is printed?
int n = 2, sum = 0;
while (n <= 12) {
sum += n;
n += 4;
}
System.out.println("n=" + n + " sum=" + sum);Show answer
Trace table:
n=2: 2 <= 12 T → sum = 2, n = 6
n=6: T → sum = 8, n = 10
n=10: T → sum = 18, n = 14
n=14: 14 <= 12 F → exit.
After the loop n is 14, not 10.
What is printed?
for (int i = 1; i <= 10; i++) {
if (i % 4 == 0) continue;
if (i == 7) break;
System.out.print(i + " ");
}Show answer
At i = 4, 4 % 4 == 0 → continue, this iteration is skipped (nothing is printed). At i = 7, break → the loop ends completely; 8, 9, 10 are never reached.
What is printed?
for (int i = 4; i >= 1; i--) {
for (int j = i; j <= 4; j++) System.out.print(j);
System.out.println();
}Show answer
34
234
1234
The outer loop runs i = 4, 3, 2, 1. The inner loop prints j from i up to 4. i = 4 → "4", i = 3 → "34", i = 2 → "234", i = 1 → "1234". println after each line.
What is printed?
int count = 0;
for (int i = 0; i < 4; i++)
for (int j = i; j < 5; j++)
count++;
System.out.println("count = " + count);Show answer
Because the inner loop starts at i, the number of iterations changes for each i: i = 0 → 5 iterations, i = 1 → 4, i = 2 → 3, i = 3 → 2. Total 5 + 4 + 3 + 2 = 14. Do not fall into the "4 × 5 = 20" trap.
What is printed?
int x = 10;
do {
System.out.print(x + " ");
x -= 4;
} while (x > 0);
System.out.println("end " + x);Show answer
do-while runs the body first and checks the condition at the end. Print 10 → x = 6 (T), print 6 → x = 2 (T), print 2 → x = -2 (F) → exit. println adds end -2 on the same line.
What is printed?
int y = 10;
while (y < 5) System.out.println("while body");
do { System.out.println("do-while body"); } while (y < 5);Show answer
The while condition is false from the start: the body never runs (0 iterations). do-while runs the body once first, then looks at the condition: at least 1 iteration.
What is printed?
int m = 50, steps = 0;
while (m != 1) {
if (m % 2 == 0) m /= 2;
else m = 3 * m + 1;
steps++;
if (steps == 4) break;
}
System.out.println(m + " " + steps);Show answer
50 is even → 25 (steps 1). 25 is odd → 76 (2). 76 → 38 (3). 38 → 19 (4), steps == 4 → break. m = 19, steps = 4.
What is printed?
for (int k = 5; k >= 1; k -= 2) {
for (int j = 1; j <= k; j++) System.out.print("#");
System.out.println();
}Show answer
###
#
The outer loop runs k = 5, 3, 1 (it drops by 2 each time and stops at -1). Each line has k #'s.
What is printed?
int p = 0;
for (int k = 1; k <= 3; k++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) break;
p += k * j;
}
}
System.out.println(p);Show answer
break ends only the loop it is in (the inner loop). For each k the inner loop runs only at j = 1: p += k. p = 1 + 2 + 3 = 6. The outer loop continues normally.
What is printed?
int e = 0;
for (int k = 0; k < 5; k++);
{ e++; }
System.out.println(e);Show answer
The ; at the end of the for line is the loop's body: the loop spins 5 times doing nothing. The { e++; } below does not belong to the loop and runs once. The result is 1, not 5.
Write a static method countDivisors(int n) that returns how many positive divisors n has. Example: countDivisors(12) returns 6 (1, 2, 3, 4, 6, 12).
Show answer
The counter pattern: start the counter at 0, check the condition in the loop, increment if it matches, return at the end.public static int countDivisors(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) count++; } return count;}Test: countDivisors(12) → 6, countDivisors(7) → 2 (prime), countDivisors(1) → 1.
Write a static void method printInverted(int n) that prints an inverted left-aligned triangle of stars with n rows (first row has n stars, last row has 1).
Show answer
The outer loop is the rows (i = 1..n), the inner loop is the stars in that row. Row i has n - i + 1 stars.public static void printInverted(int n) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n - i + 1; j++) { System.out.print("*"); } System.out.println(); }}Output of printInverted(3): three lines, with 3, 2, 1 stars in order. Alternative: write the outer loop as for (int i = n; i >= 1; i--) and use j <= i in the inner loop.
Verification: All outputs were run with JDK 26 (verify/SEN1001/W04.java and W04b.java). The spaces in the pattern outputs were checked character by character with cat -A. The scope error was obtained by compiling verify/SEN1001/err/Scope.java with javac.