SEN1001 · Week 4 · Control Statements: Part 2

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.

repetition statementloopwhilefordo...whileloop-continuation conditioncounter-controlledsentinel-controlledoff-by-one errorinfinite loopbreakcontinuenested looptrace table

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:

  1. At the start of each iteration write the condition: T or F? The moment it is F, the loop ends.
  2. The value of the counter after the loop is one step ahead: when i <= 5 finishes, i = 6.
  3. do-while runs at least once, while may not run at all.
  4. break ends the loop, continue only skips that iteration.
  5. 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 write System.out.println(i); after the loop you get a cannot find symbol error. 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.

LoopWhen is the condition checked?Minimum iterationsTypical use
whileat the start0the end point is unknown
forat the start0the number of iterations is known
do-whileat the end1menus, 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:

PatternSpacesStars
Left triangle0i
Inverted triangle0n - i + 1
Right-aligned trianglen - ii
Pyramidn - i2 * 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 ideaThe truth
for (i = 0; i <= 5; i++) is 5 iterations6 iterations; <= includes the last value
After the loop i is the last value usedOne step further: the value that broke the condition
do-while never runs if the condition is falseIt runs at least once
continue ends the loopIt only skips that iteration
A break in the inner loop also ends the outer loopOnly the inner loop
for (...); then { } is the loop bodyThe ; is the body, the block runs once
println goes inside the inner loopInside the outer loop, after the inner loop
In nested loops iterations = outer × inner alwaysIf the inner bound depends on the outer, count iteration by iteration
Forgetting i++ in a while is no problemInfinite loop

Test yourself

Exam-style questions. Solve them on paper first, then reveal the answer.

Question 1easy

What is printed?

int n = 2, sum = 0;
while (n <= 12) {
    sum += n;
    n += 4;
}
System.out.println("n=" + n + " sum=" + sum);
Show answer
n=14 sum=18

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.

Question 2medium

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
1 2 3 5 6

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.

Question 3medium

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
4
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.

Question 4hard

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
count = 14

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.

Question 5medium

What is printed?

int x = 10;
do {
    System.out.print(x + " ");
    x -= 4;
} while (x > 0);
System.out.println("end " + x);
Show answer
10 6 2 end -2

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.

Question 6easy

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
do-while body

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.

Question 7medium

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
19 4

50 is even → 25 (steps 1). 25 is odd → 76 (2). 76 → 38 (3). 38 → 19 (4), steps == 4 → break. m = 19, steps = 4.

Question 8medium

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.

Question 9hard

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
6

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.

Question 10hard

What is printed?

int e = 0;
for (int k = 0; k < 5; k++);
{ e++; }
System.out.println(e);
Show answer
1

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.

Question 11medium

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
for (int i = 1; i <= n; i++) if (n % i == 0) count++;

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.

Question 12hard

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
inner loop: for (int j = 1; j <= n - i + 1; j++)

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.

Review card

while (condition) { ... update; } 0 or more iterations, condition at the START for (int i = 1; i <= n; i++) { } when the number of iterations is known do { ... } while (condition); AT LEAST 1 iteration, condition at the END, note the ; for order: init → condition → body → update → condition → ... Iteration count: i=0;i<n → n i=1;i<=n → n i=0;i<=n → n+1 Counter after the loop: for (i=1;i<=5;i++) ends with i = 6 break → leave the loop it is in continue → skip the iteration (for still runs the update) In nested loops break ends only the INNER loop for (...); while (...); → the trailing ; is an empty body Digits: while (n > 0) { d = n % 10; ... n /= 10; } reverse: rev = rev*10 + n%10 Nested: outer = row, inner = column, println() when the inner one finishes Left triangle j<=i Inverted j<=n-i+1 Right-aligned: n-i spaces + i stars Pyramid: n-i spaces + 2i-1 If the inner loop is fixed, total = outer × inner; if it depends on the outer variable, add up iteration by iteration An i declared in a for does NOT exist outside the loop (cannot find symbol)