Chapter 8: Loops
Introduction
Learning Outcomes
Choose between for, while and do-while.
Compute with counters and accumulators.
Produce row-column patterns with nested loops.
Verify a loop step by step at its boundary values.
Loops
Parts of a Loop
- Initialization: state set up once, before the loop.
- Condition: tested before each pass (after it in do-while); false means exit.
- Body: the work done on each pass.
- Update: moves the condition toward false; forget it and the loop never ends.
Loops
The for Loop
int n = 4; int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } System.out.println(sum);
initializationconditionbodyupdate
- Use for when the number of passes is known; all four parts fit on one line.
- Order: initialization → condition → body → update → condition …
- i exists only inside the loop.
Loops · Step through the code
Code Trace: 1 + 2 + 3 + 4 with for
n = 4: we will add 1 through 4.
The accumulator starts at sum = 0 (nothing added yet).
Initialization: int i = 1 runs only once.
Condition: i <= n → 1 <= 4 → true → enter the body.
Body: sum = 0 + 1 = 1.
Update: i++ → i = 2. Then back to the condition.
Condition: i <= n → 2 <= 4 → true → enter the body.
Body: sum = 1 + 2 = 3.
Update: i++ → i = 3. Then back to the condition.
Condition: i <= n → 3 <= 4 → true → enter the body.
Body: sum = 3 + 3 = 6.
Update: i++ → i = 4. Then back to the condition.
Condition: i <= n → 4 <= 4 → true → enter the body.
Body: sum = 6 + 4 = 10.
Update: i++ → i = 5. Then back to the condition.
Condition: i <= n → 5 <= 4 → false → the loop ends.
After the loop, println prints 10. i is gone: its scope was the loop. Body ran 4 times, condition 5 times.
int n = 4; int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } System.out.println(sum);
Loops
Flexible Forms of the for Loop
| Header | Runs |
|---|---|
for (int i = 0, j = 9; i < j; i++, j--) | i and j together: (0,9) … (4,5), 5 passes |
for (int i = 0; i <= 10; i += 2) | 0 2 4 6 8 10 |
for (int i = 5; i >= 1; i--) | countdown: 5 4 3 2 1 |
int k = 0; for (;;) { // all parts empty: always true k++; if (k == 3) break; // exit is required } System.out.println(k); // 3
- Initialization, condition and update are each optional.
- Initialization can declare several variables of one type; the update can hold several comma-separated expressions.
Loops
++i vs. i++
for (int i = 0; i < 3; i++) System.out.print(i + " "); // 0 1 2 for (int i = 0; i < 3; ++i) System.out.print(i + " "); // 0 1 2
In the update part of a for, the expression's value is unused; both just add 1 to i, so there is no difference.
| Start | Expression | result | after |
|---|---|---|---|
a = 5 | b = a++ | b = 5 | a = 6 |
a = 5 | b = ++a | b = 6 | a = 6 |
idx = 0 | d[idx++] | 10 | idx = 1 |
idx = 0 | d[++idx] | 20 | idx = 1 |
i++yields the old value, then increments;++iincrements, then yields the new value.- In the table
d = {10, 20, 30}; the difference shows only when the value is used. Writei++for counters; it reads better.
Loops
The while Loop
int num = 5; int factorial = 1; while (num > 1) { factorial *= num; num--; } System.out.println(factorial);
initializationconditionbodyupdate
- The condition is checked before the body.
- If it is false at the start, the body never runs.
- Initialization goes before the loop, the update inside the body.
Loops · Step through the code
Code Trace: 5! with while
Initialization: num = 5 (we will compute 5!).
A product accumulator starts at 1 (with 0 the result would always be 0).
Condition: 5 > 1 → true → run the body.
factorial = 1 × 5 = 5.
Update: num-- → 4. The condition moves toward false.
Condition: 4 > 1 → true → run the body.
factorial = 5 × 4 = 20.
Update: num-- → 3. The condition moves toward false.
Condition: 3 > 1 → true → run the body.
factorial = 20 × 3 = 60.
Update: num-- → 2. The condition moves toward false.
Condition: 2 > 1 → true → run the body.
factorial = 60 × 2 = 120.
Update: num-- → 1. The condition moves toward false.
Condition: 1 > 1 → false → exit the loop.
120 is printed: 5 × 4 × 3 × 2 = 120. The body ran 4 times; no need to multiply by 1.
int num = 5; int factorial = 1; while (num > 1) { factorial *= num; num--; } System.out.println(factorial);
Loops
The do-while Loop
Scanner in = new Scanner(System.in); int choice; do { System.out.print("Choice (1/0): "); choice = in.nextInt(); if (choice == 1) System.out.println("Hello!"); } while (choice != 0); System.out.println("Goodbye");
initializationconditionbodyupdate
- The condition is checked after the body → the body runs at least once.
- The natural choice for menus and input validation.
- Don't forget the semicolon after
while (…);.
Loops · Step through the code
Code Trace: a do-while menu (input 1, 2, 0)
A Scanner reads from the keyboard (import java.util.Scanner; at the top). The user will type 1, 2, 0.
choice is declared without a value; that's fine, since the condition is first tested after the body.
Pass 1: the body runs without checking the condition; the menu is printed.
The user types 1 → choice = 1.
choice == 1 → true: «Hello!» is printed.
Condition: 1 != 0 → true → back to the top.
Pass 2: the body runs without checking the condition; the menu is printed.
The user types 2 → choice = 2.
choice == 1 → false: nothing happens.
Condition: 2 != 0 → true → back to the top.
Pass 3: the body runs without checking the condition; the menu is printed.
The user types 0 → choice = 0.
choice == 1 → false: nothing happens.
Condition: 0 != 0 → false → the loop ends.
The body ran 3 times and the condition was tested 3 times (a while would test it once more than the body runs).
Scanner in = new Scanner(System.in); int choice; do { System.out.print("Choice (1/0): "); choice = in.nextInt(); if (choice == 1) System.out.println("Hello!"); } while (choice != 0); System.out.println("Goodbye");
Loops
Choosing a Loop
| Situation | Choice |
|---|---|
| Count from 1 to n, repeat n times | for |
| Process digits until the number is 0 | while |
| Show a menu, ask until the input is valid | do-while |
| Add until the user types “0” | while / do-while |
Each can be rewritten as the others; choose for readability.
Branching
break and continue
for (int i = 1; i <= 10; i++) { if (i % 3 == 0) continue; if (i == 8) break; System.out.print(i + " "); } System.out.println("| done");
- continue: skips the rest of the pass and goes to the update (i++).
- break: ends the nearest enclosing loop at once.
- Overuse makes the flow hard to follow.
Branching · Step through the code
Code Trace: break and continue
i = 1: 1 % 3 = 1 → false; 1 == 8 → false. Both checks pass.
1 is printed.
i = 2: 2 % 3 = 2 → false; 2 == 8 → false. Both checks pass.
2 is printed.
i = 3: 3 % 3 == 0 → true → continue: print is skipped, straight to i++.
i = 4: 4 % 3 = 1 → false; 4 == 8 → false. Both checks pass.
4 is printed.
i = 5: 5 % 3 = 2 → false; 5 == 8 → false. Both checks pass.
5 is printed.
i = 6: 6 % 3 == 0 → true → continue: print is skipped, straight to i++.
i = 7: 7 % 3 = 1 → false; 7 == 8 → false. Both checks pass.
7 is printed.
i = 8: 8 % 3 = 2 → false; 8 == 8 → true → break: the loop ends here; 9 and 10 are never reached.
The loop ended with break; execution continues after the loop.
for (int i = 1; i <= 10; i++) { if (i % 3 == 0) continue; if (i == 8) break; System.out.print(i + " "); } System.out.println("| done");
Branching · Step through the code
Labeled break outer: leave both loops at once
i = 1, j = 1: 1·1 = 1 ≠ 4, 1 1 is printed.
j = 2: 1·2 = 2 ≠ 4 → 1 2 is printed.
j = 3: 1·3 = 3 ≠ 4 → 1 3 is printed; the inner loop ends.
i = 2; the inner loop restarts: j = 1, 2·1 = 2 ≠ 4 → 2 1 is printed.
i = 2, j = 2: 2·2 = 4 → break outer. Without printing, control leaves both loops; i = 3 is never tried.
A labeled break jumps to the line after the outer loop: done is printed. Output: 4 number lines + done.
outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i * j == 4) break outer; System.out.println(i + " " + j); } } System.out.println("done");
Branching · Step through the code
Comparison: a plain break ends only the inner loop
i = 1: 1·j ≠ 4 for j = 1, 2, 3; 1 1, 1 2, 1 3 are printed.
i = 2, j = 1: 2·1 = 2 ≠ 4 → 2 1 is printed.
i = 2, j = 2: 2·2 = 4 → a plain break ends only the inner loop; the outer loop goes on.
i++ → 3; the inner loop restarts: j = 1 → 3 1 is printed.
j = 2 and j = 3: 3·2 = 6, 3·3 = 9 ≠ 4 → 3 2 and 3 3 are printed.
The outer loop ends too and done is printed. A plain break gives 7 number lines, a labeled break 4.
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i * j == 4) break; System.out.println(i + " " + j); } } System.out.println("done");
Loops
Infinite Loops
- If the condition never becomes false, the loop never ends: the program seems “frozen”.
- Note: with
i--theinteventually wraps around and the loop stops after about 2.1 billion passes; in practice it is infinite. - The counter may move the wrong way or never be updated at all.
- Deliberate
while (true)loops still need abreakcondition inside. If a program hangs, stop it with Ctrl+C.
Loops · Step through the code
The double Counter Trap: x += 0.1
Start: n = 0. The goal: step by 0.1 and loop 10 times.
x = 0.0, condition 0.0 < 1.0 → true.
Body: n = 1.
Update: x = 0.1. 0.1 has no exact binary representation; small errors accumulate.
End of pass 10 (8 passes skipped here): n = 10, x = 0.8999999999999999.
Update: x = 0.9999999999999999, not exactly 1.0. The condition is true: one extra pass.
Pass 11: n = 11.
x = 1.0999999999999999, the condition is false → the loop ends.
11 is printed; 10 was expected.
int n = 0; for (double x = 0; x < 1.0; x += 0.1) { n++; } System.out.println(n);
With x != 1.0 the loop would never end, since x never equals 1.0 exactly. Use an int counter, not a real number.
Verification
Loop Invariants
- A property that holds at the start of every pass.
- In the sum loop:
sum = 1 + 2 + … + (i − 1). - When the loop ends (i = n + 1), the invariant tells us the result is correct.
No number processed yet: sum = 0 (the empty sum). The invariant holds from the start.
At the start of pass i = 2, sum holds 1 … 1 added up: 1.
At the start of pass i = 3, sum holds 1 … 2 added up: 3.
At the start of pass i = 4, sum holds 1 … 3 added up: 6.
i = 5 → condition false. The invariant still holds: sum = 1 + 2 + 3 + 4 = 10 → the result is correct.
Verification
Off-by-One Errors (count 1 to 5)
<vs.<=, or starting at 0 vs. 1, means one pass too few or too many (“off-by-one”).- Test: check the first pass, the last pass and the pass count by hand.
Verification · Step through the code
Checking the Bounds: i < 5 → 5 passes
Start: i = 0, count = 0. Condition 0 < 5 → true.
Pass 1: prints i = 0, count becomes 1.
Pass 2: prints i = 1, count becomes 2.
Pass 3: prints i = 2, count becomes 3.
Pass 4: prints i = 3, count becomes 4.
Pass 5: prints i = 4, count becomes 5.
i++ → 5; 5 < 5 → false, the loop ends. Exactly 5 passes: i = 0…4.
int count = 0; for (int i = 0; i < 5; i++) { System.out.print(i + " "); count++; } System.out.println("| rounds: " + count);
Verification · Step through the code
Off-by-One: i <= 5 → 6 passes
Start: i = 0, count = 0. Condition 0 <= 5 → true.
Pass 1: prints i = 0, count becomes 1.
Pass 2: prints i = 1, count becomes 2.
Pass 3: prints i = 2, count becomes 3.
Pass 4: prints i = 3, count becomes 4.
Pass 5: prints i = 4, count becomes 5.
Pass 6: prints i = 5, count becomes 6.
i++ → 6; 6 <= 5 → false. The <= caused one extra pass: count = 6, not the expected 5.
int count = 0; for (int i = 0; i <= 5; i++) { System.out.print(i + " "); count++; } System.out.println("| rounds: " + count);
Example
Counting Digits
int num = -507; long rest = num; if (rest < 0) rest = -rest; int digits = 0; do { digits++; rest /= 10; } while (rest > 0); System.out.println(digits);
- Each
/ 10drops the last digit; we count the divisions. - Thanks to do-while, 0 also counts as 1 digit; no special case needed.
- The long copy avoids overflow when negating an extreme value such as
-2147483648.
Examples · Step through the code
Code Trace: counting digits (num = −507)
Let's try a negative number: num = −507.
The int is copied into a long (the negation of −2147483648 does not fit in an int, but fits in a long).
−507 < 0 → true → rest = 507. The sign does not change the digit count.
Counter digits = 0.
Body: one digit counted → digits = 1.
rest = 507 / 10 = 50 (integer division drops the last digit).
Condition: 50 > 0 → true → repeat.
Body: one digit counted → digits = 2.
rest = 50 / 10 = 5 (integer division drops the last digit).
Condition: 5 > 0 → true → repeat.
Body: one digit counted → digits = 3.
rest = 5 / 10 = 0 (integer division drops the last digit).
Condition: 0 > 0 → false → done.
3 is printed. For num = 0, do-while would still run the body once → 1 digit (correct).
int num = -507; long rest = num; if (rest < 0) rest = -rest; int digits = 0; do { digits++; rest /= 10; } while (rest > 0); System.out.println(digits);
Example
Sum of Digits
int num = 725; long rest = num; if (rest < 0) rest = -rest; int sum = 0; while (rest > 0) { sum += (int) (rest % 10); rest /= 10; } System.out.println(sum);
% 10gives the last digit./ 10removes the processed last digit.- A while is enough here: for 0 the body never runs and sum stays 0 (correct).
Examples · Step through the code
Code Trace: sum of digits (num = 725)
A number with digits 7, 2 and 5: 725.
A copy to work on: rest = 725.
725 < 0 → false: the sign stays.
Accumulator sum = 0.
Condition: 725 > 0 → true.
Last digit 725 % 10 = 5; sum = 0 + 5 = 5.
rest = 725 / 10 = 72: the processed digit is dropped.
Condition: 72 > 0 → true.
Last digit 72 % 10 = 2; sum = 5 + 2 = 7.
rest = 72 / 10 = 7: the processed digit is dropped.
Condition: 7 > 0 → true.
Last digit 7 % 10 = 7; sum = 7 + 7 = 14.
rest = 7 / 10 = 0: the processed digit is dropped.
Condition: 0 > 0 → false.
14 is printed: 7 + 2 + 5 = 14. num is unchanged; only its copy (rest) was used up.
int num = 725; long rest = num; if (rest < 0) rest = -rest; int sum = 0; while (rest > 0) { sum += (int) (rest % 10); rest /= 10; } System.out.println(sum);
Examples · Step through the code
Reversing a Number and Palindromes (1221)
A number that reads the same backward is a palindrome. Let's try 1221.
We work on a copy; the reversed number is built up from 0.
Condition: 1221 > 0 → true.
digit = 1221 % 10 = 1; rev = 0 × 10 + 1 = 1 (earlier digits shift one place left).
rest = 1221 / 10 = 122.
Condition: 122 > 0 → true.
digit = 122 % 10 = 2; rev = 1 × 10 + 2 = 12 (earlier digits shift one place left).
rest = 122 / 10 = 12.
Condition: 12 > 0 → true.
digit = 12 % 10 = 2; rev = 12 × 10 + 2 = 122 (earlier digits shift one place left).
rest = 12 / 10 = 1.
Condition: 1 > 0 → true.
digit = 1 % 10 = 1; rev = 122 × 10 + 1 = 1221 (earlier digits shift one place left).
rest = 1 / 10 = 0.
Condition: 0 > 0 → false.
The reversed number 1221 is printed.
1221 == 1221 → true: 1221 is a palindrome. (For 123 the reverse is 321 → false.)
int num = 1221; int rest = num, rev = 0; while (rest > 0) { int digit = rest % 10; rev = rev * 10 + digit; rest /= 10; } System.out.println(rev); System.out.println(rev == num); // palindrome?
Examples · Step through the code
Armstrong Numbers: 153 = 1³ + 5³ + 3³
Armstrong number: equals the sum of its digits each raised to the number of digits. 153 has three digits → cubes.
rest = 153, sum = 0.
Condition: 153 > 0 → true.
r = 3; sum = 0 + 3×3×3 = 27.
rest /= 10 → 15.
Condition: 15 > 0 → true.
r = 5; sum = 27 + 5×5×5 = 152.
rest /= 10 → 1.
Condition: 1 > 0 → true.
r = 1; sum = 152 + 1×1×1 = 153.
rest /= 10 → 0.
Condition: 0 > 0 → false.
1 + 125 + 27 = 153 → true. The other 3-digit Armstrong numbers: 370, 371, 407.
int num = 153; int rest = num, sum = 0; while (rest > 0) { int r = rest % 10; sum += r * r * r; // 3 digits: cube rest /= 10; } System.out.println(sum == num);
Examples · Step through the code
Perfect Numbers: 28
Perfect number: equals the sum of its divisors other than itself (6 = 1 + 2 + 3). Let's try 28.
The divisor sum starts at 0. Apart from n itself, the largest divisor is at most n / 2 = 14.
i = 1: 28 % 1 = 0 → divisor, sum = 1.
i = 2: 28 % 2 = 0 → divisor, sum = 3.
i = 3: 28 % 3 = 1 → not a divisor.
i = 4: 28 % 4 = 0 → divisor, sum = 7.
i = 5: 28 % 5 = 3 → not a divisor.
i = 6: 28 % 6 = 4 → not a divisor.
i = 7: 28 % 7 = 0 → divisor, sum = 14.
i = 8: 28 % 8 = 4 → not a divisor.
i = 9: 28 % 9 = 1 → not a divisor.
i = 10: 28 % 10 = 8 → not a divisor.
i = 11: 28 % 11 = 6 → not a divisor.
i = 12: 28 % 12 = 4 → not a divisor.
i = 13: 28 % 13 = 2 → not a divisor.
i = 14: 28 % 14 = 0 → divisor, sum = 28.
i = 15 <= 14 → false: the loop ends.
1 + 2 + 4 + 7 + 14 = 28 → true. The next perfect numbers: 496, 8128.
int n = 28; int sum = 0; for (int i = 1; i <= n / 2; i++) { if (n % i == 0) sum += i; } System.out.println(sum == n);
Examples · Step through the code
Decimal to Binary: 13 → 1101
Converting 13 to binary: divide by 2 repeatedly and collect the remainders.
We build the binary result from decimal digits (1s and 0s); place = 1 is the ones place.
Condition: 13 > 0 → true.
13 % 2 = 1 → bin += 1 × 1 → 1.
Next bit is one place left: place = 10; n = n / 2 = 6.
Condition: 6 > 0 → true.
6 % 2 = 0 → bin += 0 × 10 → 1.
Next bit is one place left: place = 100; n = n / 2 = 3.
Condition: 3 > 0 → true.
3 % 2 = 1 → bin += 1 × 100 → 101.
Next bit is one place left: place = 1000; n = n / 2 = 1.
Condition: 1 > 0 → true.
1 % 2 = 1 → bin += 1 × 1000 → 1101.
Next bit is one place left: place = 10000; n = n / 2 = 0.
Condition: 0 > 0 → false.
1101 is printed: 1·8 + 1·4 + 0·2 + 1·1 = 13. (For large numbers int overflows; build the result as a String instead.)
int n = 13; int bin = 0, place = 1; while (n > 0) { bin += (n % 2) * place; place *= 10; n /= 2; } System.out.println(bin); // 1101
Example
Exponentiation
int base = 2, exp = 4; int result = 1; for (int i = 0; i < exp; i++) { result *= base; } System.out.println(result);
- The loop runs exactly exp times; each pass multiplies by the base once.
- If exp = 0 the loop never runs and result stays 1 (2⁰ = 1).
- Negative exponents are not handled; large results overflow int.
Examples · Step through the code
Code Trace: 2⁴
We will compute 2⁴: base = 2, exp = 4.
1 is the identity for multiplication: result = 1 (= 2⁰).
Initialization: i = 0. The loop will run exp times (0, 1, 2, 3).
Condition: 0 < 4 → true.
result = 1 × 2 = 2 (= 21).
Update: i = 1.
Condition: 1 < 4 → true.
result = 2 × 2 = 4 (= 22).
Update: i = 2.
Condition: 2 < 4 → true.
result = 4 × 2 = 8 (= 23).
Update: i = 3.
Condition: 3 < 4 → true.
result = 8 × 2 = 16 (= 24).
Update: i = 4.
Condition: 4 < 4 → false.
16 is printed. Invariant: at the start of each pass, result = 2i.
int base = 2, exp = 4; int result = 1; for (int i = 0; i < exp; i++) { result *= base; } System.out.println(result);
Example
Prime Numbers
int n = 29; boolean prime = n >= 2; for (int i = 2; prime && i <= n / i; i++) { if (n % i == 0) prime = false; } System.out.println(prime);
- 0 and 1 are not prime:
prime = n >= 2. - Divisors need only be checked up to √n:
i <= n / i≡ i × i ≤ n (no overflow risk). - Thanks to
prime &&, the loop stops once a divisor is found.
Examples · Step through the code
Code Trace: is 29 prime?
Is n = 29 prime?
29 >= 2 → true. Assume prime until proven otherwise.
Start: the first divisor candidate is i = 2.
Condition: true && 2 <= 29/2 = 14 → true.
29 % 2 = 1 → not a divisor.
Update: i = 3.
Condition: true && 3 <= 29/3 = 9 → true.
29 % 3 = 2 → not a divisor.
Update: i = 4.
Condition: true && 4 <= 29/4 = 7 → true.
29 % 4 = 1 → not a divisor.
Update: i = 5.
Condition: true && 5 <= 29/5 = 5 → true.
29 % 5 = 4 → not a divisor.
Update: i = 6.
Condition: true && 6 <= 29/6 = 4 → false: we are past √29, so no larger divisor needs checking.
true is printed. 4 candidates were tried.
int n = 29; boolean prime = n >= 2; for (int i = 2; prime && i <= n / i; i++) { if (n % i == 0) prime = false; } System.out.println(prime);
Examples · Step through the code
Code Trace (cont.): is 21 prime?
Is n = 21 prime?
21 >= 2 → true. Assume prime until proven otherwise.
Start: the first divisor candidate is i = 2.
Condition: true && 2 <= 21/2 = 10 → true.
21 % 2 = 1 → not a divisor.
Update: i = 3.
Condition: true && 3 <= 21/3 = 7 → true.
21 % 3 = 0 → divisor found: prime = false.
Update: i = 4.
Condition: prime = false → && short-circuits, i <= n / i is never evaluated → the loop ends.
false is printed. The loop stopped as soon as a divisor was found.
int n = 21; boolean prime = n >= 2; for (int i = 2; prime && i <= n / i; i++) { if (n % i == 0) prime = false; } System.out.println(prime);
Examples · Step through the code
Listing the Primes from 1 to n (n = 20)
For each k from 2 to 20, a primality test (inner loop) runs.
k = 2: inner loop never runs (2 > k / 2) → prime = true → printed.
k = 3: inner loop never runs (2 > k / 2) → prime = true → printed.
k = 4: 4 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 5: no divisor in 2 … 2 → prime = true → printed.
k = 6: 6 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 7: no divisor in 2 … 2 → prime = true → printed.
k = 8: 8 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 9: 9 % 3 = 0 → prime = false, break (the inner loop ends early).
k = 10: 10 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 11: no divisor in 2 … 3 → prime = true → printed.
k = 12: 12 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 13: no divisor in 2 … 3 → prime = true → printed.
k = 14: 14 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 15: 15 % 3 = 0 → prime = false, break (the inner loop ends early).
k = 16: 16 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 17: no divisor in 2 … 4 → prime = true → printed.
k = 18: 18 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 19: no divisor in 2 … 4 → prime = true → printed.
k = 20: 20 % 2 = 0 → prime = false, break (the inner loop ends early).
k = 21 > 20: done. There are 8 primes in 2..20. (The sieve of Eratosthenes is faster.)
int n = 20; for (int k = 2; k <= n; k++) { boolean prime = true; for (int i = 2; i <= k / i; i++) { if (k % i == 0) { prime = false; break; } } if (prime) System.out.print(k + " "); }
Example
The Fibonacci Sequence
int terms = 5; long a = 0, b = 1; for (int i = 0; i < terms; i++) { System.out.print(a + " "); long next = a + b; a = b; b = next; }
- Each term is the sum of the previous two: 0 1 1 2 3 5 8 …
- The update order keeps both previous values; writing
b = nextfirst would lose the old b. - The sequence grows fast; even long overflows after term 93.
Examples · Step through the code
Code Trace: the first 5 Fibonacci numbers
We will print the first 5 Fibonacci numbers.
The first two terms: a = 0, b = 1.
i = 0 < 5 → true. Print the next term, a = 0.
next = 0 + 1 = 1.
Shift: a = 1, b = 1. Order matters: a = b first, then b = next. Then i++.
i = 1 < 5 → true. Print the next term, a = 1.
next = 1 + 1 = 2.
Shift: a = 1, b = 2. Order matters: a = b first, then b = next. Then i++.
i = 2 < 5 → true. Print the next term, a = 1.
next = 1 + 2 = 3.
Shift: a = 2, b = 3. Order matters: a = b first, then b = next. Then i++.
i = 3 < 5 → true. Print the next term, a = 2.
next = 2 + 3 = 5.
Shift: a = 3, b = 5. Order matters: a = b first, then b = next. Then i++.
i = 4 < 5 → true. Print the next term, a = 3.
next = 3 + 5 = 8.
Shift: a = 5, b = 8. Order matters: a = b first, then b = next. Then i++.
Condition: 5 < 5 → false → the loop ends. Output: 0 1 1 2 3.
int terms = 5; long a = 0, b = 1; for (int i = 0; i < terms; i++) { System.out.print(a + " "); long next = a + b; a = b; b = next; }
Examples · Step through the code
Number Guessing Game (while + Random + Scanner)
Random generates random numbers (import java.util.Random; and java.util.Scanner at the top).
A Scanner to read from the keyboard.
nextInt(100) gives 0..99; +1 makes it 1..100. This run picked target = 37 (it differs every run).
guess = 0 can never be the target → the loop is sure to start.
Condition: 0 != 37 → true.
The user types 50; tries = 1.
50 > 37 → «Lower». Possible range 1..49. Guessing the middle each time halves the range.
Condition: 50 != 37 → true.
The user types 25; tries = 2.
25 < 37 → «Higher». Possible range 26..49.
Condition: 25 != 37 → true.
The user types 37; tries = 3.
37 is neither smaller nor larger: both ifs are false, no message.
Condition: 37 != 37 → false → the loop ends.
The number of passes is unknown in advance → while is the right choice.
Random rnd = new Random(); Scanner in = new Scanner(System.in); int target = rnd.nextInt(100) + 1; // 1..100 int guess = 0, tries = 0; while (guess != target) { guess = in.nextInt(); tries++; if (guess < target) System.out.println("Higher"); if (guess > target) System.out.println("Lower"); } System.out.println("Got it in " + tries + " tries");
Examples · Step through the code
Sentinel Value: while (true) + break, input 5, 3, 0
Input queue (numbers to be typed): 5, 3, 0. The condition is true, so the loop never ends by itself; break provides the exit.
nextInt() reads 5 from the queue. 5 == 0 → false, no break.
sum = 0 + 5 = 5. Back to the top (true).
nextInt() → 3. 3 == 0 → false.
sum = 5 + 3 = 8.
nextInt() → 0 (the sentinel). 0 == 0 → true → break: exit the loop; 0 is not added.
Sum: 8 is printed. A sentinel marks the end of the data and is not part of it.
Scanner sc = new Scanner(System.in); int sum = 0; while (true) { int num = sc.nextInt(); if (num == 0) break; sum += num; } System.out.println("Sum: " + sum);
Loops
Nested Loops
for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) { System.out.printf("(%d,%d) ", row, col); } System.out.println(); }
- The inner loop runs to completion on every pass of the outer loop.
- The body runs rows × cols = 3 × 4 = 12 times.
Loops · Step through the code
Code Trace: a 3 × 4 grid
Outer loop row = 0; the inner loop starts at col = 0 → (0,0).
col++ → 1 < 4 → true → (0,1) is printed.
col++ → 2 < 4 → true → (0,2) is printed.
col++ → 3 < 4 → true → (0,3) is printed.
col = 4 < 4 → false: the inner loop is done. println ends the line.
row++ → row = 1; the inner loop restarts at col = 0.
col++ → 1 < 4 → true → (1,1) is printed.
col++ → 2 < 4 → true → (1,2) is printed.
col++ → 3 < 4 → true → (1,3) is printed.
col = 4 < 4 → false: the inner loop is done. println ends the line.
row++ → row = 2; the inner loop restarts at col = 0.
col++ → 1 < 4 → true → (2,1) is printed.
col++ → 2 < 4 → true → (2,2) is printed.
col++ → 3 < 4 → true → (2,3) is printed.
col = 4 < 4 → false: the inner loop is done. println ends the line.
row = 3 < 3 → false: the outer loop is done too. 3 × 4 = 12 printf calls in all.
for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) { System.out.printf("(%d,%d) ", row, col); } System.out.println(); }
Loops · Step through the code
Multiplication Table (nested loops, 3 × 3)
Outer loop i = 1; inner loop starts at j = 1: 1 × 1 = 1.
j = 2: 1 × 2 = 2, right-aligned in a 4-character field.
j = 3: 1 × 3 = 3, right-aligned in a 4-character field.
j = 4 <= 3 → false; println ends the line.
Outer loop i = 2; inner loop starts at j = 1: 2 × 1 = 2.
j = 2: 2 × 2 = 4, right-aligned in a 4-character field.
j = 3: 2 × 3 = 6, right-aligned in a 4-character field.
j = 4 <= 3 → false; println ends the line.
Outer loop i = 3; inner loop starts at j = 1: 3 × 1 = 3.
j = 2: 3 × 2 = 6, right-aligned in a 4-character field.
j = 3: 3 × 3 = 9, right-aligned in a 4-character field.
j = 4 <= 3 → false; println ends the line.
i = 4 <= 3 → false. Change the bounds to 10 for the classic 10 × 10 table.
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.printf("%4d", i * j); } System.out.println(); }
Example
Solving Pattern Problems
- Draw the expected output for a small n (e.g. 4) on grid paper.
- Tabulate how many spaces and how many characters each row has.
- Relate the counts to the row number (3, 2, 1, 0 → n − row).
- Outer loop = row; one inner loop per part.
Example
Growing Triangle
int n = 4;
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.println();
}- Row r gets r stars.
- The inner loop's upper bound is the outer loop variable.
Examples · Step through the code
Code Trace: growing triangle (n = 4)
A triangle of n = 4 rows. Each grid cell is one character.
row = 1: inner loop col = 1 … 1 → 1 star(s) on this row.
col = 2 <= 1 → false. println moves to the next line.
row = 2: inner loop col = 1 … 2 → 2 star(s) on this row.
col = 2 <= 2 → true → *
col = 3 <= 2 → false. println moves to the next line.
row = 3: inner loop col = 1 … 3 → 3 star(s) on this row.
col = 2 <= 3 → true → *
col = 3 <= 3 → true → *
col = 4 <= 3 → false. println moves to the next line.
row = 4: inner loop col = 1 … 4 → 4 star(s) on this row.
col = 2 <= 4 → true → *
col = 3 <= 4 → true → *
col = 4 <= 4 → true → *
col = 5 <= 4 → false. println moves to the next line.
row = 5 <= 4 → false: done. 1 + 2 + 3 + 4 = 10 stars in all.
int n = 4; for (int row = 1; row <= n; row++) { for (int col = 1; col <= row; col++) { System.out.print("*"); } System.out.println(); }
Example
Right-Aligned Triangle
int n = 3;
for (int row = 1; row <= n; row++) {
for (int space = 0; space < n - row; space++)
System.out.print(" ");
for (int star = 0; star < row; star++)
System.out.print("*");
System.out.println();
}- Each row has a spaces part and a characters part.
- Spaces shrink as stars grow.
Examples · Step through the code
Code Trace: right-aligned triangle (n = 3)
n = 3. Each row: first n - row spaces, then row stars.
row = 1: 2 spaces needed. space = 0 → ' ' is printed.
space = 1 < 2 → ' ' is printed.
Spaces done; 1 star(s): star = 0 → *
Row complete (every row has n = 3 characters): println.
row = 2: 1 space needed. space = 0 → ' ' is printed.
Spaces done; 2 star(s): star = 0 → *
star = 1 < 2 → *
Row complete (every row has n = 3 characters): println.
row = 3: space < 3 − 3 = 0 → false: no spaces on this row.
Spaces done; 3 star(s): star = 0 → *
star = 1 < 3 → *
star = 2 < 3 → *
Row complete (every row has n = 3 characters): println.
int n = 3; for (int row = 1; row <= n; row++) { for (int space = 0; space < n - row; space++) System.out.print(" "); for (int star = 0; star < row; star++) System.out.print("*"); System.out.println(); }
Example
Counts per Row
| Pattern | Spaces | Characters |
|---|---|---|
| Growing triangle | 0 | row |
| Shrinking triangle | 0 | n - row + 1 |
| Right-aligned | n - row | row |
| Pyramid | n - row | 2 × row - 1 |
Example
Number Triangle
int n = 4;
for (int row = 1; row <= n; row++) {
for (int value = 1; value <= row; value++) {
System.out.print(value + " ");
}
System.out.println();
}- The printed value comes from the column variable.
- The same structure produces numbers instead of characters.
Examples · Step through the code
Code Trace: number triangle (n = 4)
Each cell gets one value + " " (number and space).
row = 1: value runs 1 to 1. value = 1 → “1 ”
value = 2 <= 1 → false; println.
row = 2: value runs 1 to 2. value = 1 → “1 ”
value = 2 → “2 ” (the printed number is the inner loop variable).
value = 3 <= 2 → false; println.
row = 3: value runs 1 to 3. value = 1 → “1 ”
value = 2 → “2 ” (the printed number is the inner loop variable).
value = 3 → “3 ” (the printed number is the inner loop variable).
value = 4 <= 3 → false; println.
row = 4: value runs 1 to 4. value = 1 → “1 ”
value = 2 → “2 ” (the printed number is the inner loop variable).
value = 3 → “3 ” (the printed number is the inner loop variable).
value = 4 → “4 ” (the printed number is the inner loop variable).
value = 5 <= 4 → false; println.
int n = 4; for (int row = 1; row <= n; row++) { for (int value = 1; value <= row; value++) { System.out.print(value + " "); } System.out.println(); }
Example
Hollow Square
int n = 4; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1) System.out.print("*"); else System.out.print(" "); } System.out.println(); }
- Only the first/last row or first/last column gets a star.
||: one of the four conditions being true is enough.- Other cells get a space; otherwise the square shifts.
Examples · Step through the code
Code Trace: hollow square (n = 4)
n = 4. Edge: first/last row (i = 0, 3) or first/last column (j = 0, 3).
i = 0, j = 0: i == 0 → true → *
i = 0, j = 1: i == 0 → true → *
i = 0, j = 2: i == 0 → true → *
i = 0, j = 3: i == 0 → true → *
j = 4 < 4 → false; println.
i = 1, j = 0: j == 0 → true → *
i = 1, j = 1: all four conditions false → else → space
i = 1, j = 2: all four conditions false → else → space
i = 1, j = 3: j == 3 → true → *
j = 4 < 4 → false; println.
int n = 4; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1) System.out.print("*"); else System.out.print(" "); } System.out.println(); }
Examples · Step through the code
Code Trace (cont.): rows 2 and 3
i = 2, j = 0: j == 0 → true → *
i = 2, j = 1: all four conditions false → else → space
i = 2, j = 2: all four conditions false → else → space
i = 2, j = 3: j == 3 → true → *
j = 4 < 4 → false; println.
i = 3, j = 0: i == 3 → true → *
i = 3, j = 1: i == 3 → true → *
i = 3, j = 2: i == 3 → true → *
i = 3, j = 3: i == 3 → true → *
j = 4 < 4 → false; println.
i = 4 < 4 → false: the square is done. 12 of the 16 cells are edges.
int n = 4; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1) System.out.print("*"); else System.out.print(" "); } System.out.println(); }
Example
Common Mistakes
- Putting println in the inner loop prints each character on its own line.
- < vs. <= yields one character too few or too many.
- Printing spaces after the stars flips the alignment.
- Changing the outer variable in the inner loop breaks the flow.
Example
Designing Tests
- Pick a normal value for each problem.
- Test 0, 1, negatives and values near the upper limit separately.
- Work out the expected result without running the code.
- Trace the variables pass by pass to find the first deviation.
| digit count test | number | expected |
|---|---|---|
| Normal | 4096 | 4 |
| Zero | 0 | 1 |
| Negative | −507 | 3 |
| Extreme | −2147483648 | 10 |
Summary
Chapter Summary
- Every loop has initialization, condition, body and update parts.
- Use for when the pass count is known, while while a condition holds, do-while when at least one pass is needed.
- Counter and accumulator patterns recur in digit, power and series problems.
- In nested loops the outer loop produces rows, the inner loop the items in each row.
- Digit pattern (
% 10,/ 10): digit count, reversing, palindromes, Armstrong; divisor pattern: primes and perfect numbers. - Test loops by tracing them by hand with 0, 1 and boundary values.
Summary
Review Questions
- What is the key difference between while and do-while?
- What do break and continue do?
- What are % 10 and / 10 for in the sum of digits?
- Why is the inner loop's upper bound the row variable in the growing triangle?
- How does the output change if println is inside the inner loop?
Summary
Exercises
- Read numbers until 0 is entered and print their sum and average (while).
- Find the sum of the numbers from 1 to 100 divisible by 3 or 5 (answer: 2418).
- Draw an n-row pyramid: row r has n − r spaces and 2r − 1 stars (trace it by hand for n = 4).
- Compute the factorial of a number with for; why doesn't 13! fit in an int? Try long.
- Use do-while to keep asking until the user enters a score from 1 to 5.
- List all Armstrong (3-digit) and perfect numbers in 1..1000.
Summary
References
- Deitel and Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
- Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, The Java Tutorials: while and do-while, for, Branching Statements.
- Sedgewick and Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.3 Conditionals and Loops.
- Downey and Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online edition).