Chapter 8: Loops

Computer Fundamentals and Introduction to Programming
forwhiledo-whileNested loopsExamples
Sercan KÜLCÜ · Giresun University

Introduction

Learning Outcomes

Loops

Choose between for, while and do-while.

Patterns

Compute with counters and accumulators.

Nesting

Produce row-column patterns with nested loops.

Tracing

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.
These four colors mean the same thing throughout the chapter.
initializationcount = 1count <= n ?conditionbodydo workupdatecount++truerepeatfalsenext statement

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.
initializationint i = 1i <= nconditionbodysum += iupdatei++truerepeatfalseprintln(sum)

Loops · Step through the code

Code Trace: 1 + 2 + 3 + 4 with for

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4

n = 4: we will add 1 through 4.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum0

The accumulator starts at sum = 0 (nothing added yet).

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum0i1

Initialization: int i = 1 runs only once.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum0i1

Condition: i <= n → 1 <= 4 → true → enter the body.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum1i1

Body: sum = 0 + 1 = 1.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum1i2

Update: i++ → i = 2. Then back to the condition.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum1i2

Condition: i <= n → 2 <= 4 → true → enter the body.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum3i2

Body: sum = 1 + 2 = 3.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum3i3

Update: i++ → i = 3. Then back to the condition.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum3i3

Condition: i <= n → 3 <= 4 → true → enter the body.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum6i3

Body: sum = 3 + 3 = 6.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum6i4

Update: i++ → i = 4. Then back to the condition.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum6i4

Condition: i <= n → 4 <= 4 → true → enter the body.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum10i4

Body: sum = 6 + 4 = 10.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum10i5

Update: i++ → i = 5. Then back to the condition.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum10i5

Condition: i <= n → 5 <= 4 → false → the loop ends.

int i = 1initializationi <= nconditionsum += ibodyi++updatetruerepeat (to condition)falseprintln(sum)after the loopn4sum10

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

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

StartExpressionresultafter
a = 5b = a++b = 5a = 6
a = 5b = ++ab = 6a = 6
idx = 0d[idx++]10idx = 1
idx = 0d[++idx]20idx = 1
  • i++ yields the old value, then increments; ++i increments, then yields the new value.
  • In the table d = {10, 20, 30}; the difference shows only when the value is used. Write i++ 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.
initializationnum = 5factorial = 1num > 1conditionbodyfactorial *= numupdatenum--truerepeatfalseprintln(factorial)

Loops · Step through the code

Code Trace: 5! with while

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum5

Initialization: num = 5 (we will compute 5!).

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum5factorial1

A product accumulator starts at 1 (with 0 the result would always be 0).

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum5factorial1

Condition: 5 > 1 → true → run the body.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum5factorial5

factorial = 1 × 5 = 5.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum4factorial5

Update: num-- → 4. The condition moves toward false.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum4factorial5

Condition: 4 > 1 → true → run the body.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum4factorial20

factorial = 5 × 4 = 20.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum3factorial20

Update: num-- → 3. The condition moves toward false.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum3factorial20

Condition: 3 > 1 → true → run the body.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum3factorial60

factorial = 20 × 3 = 60.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum2factorial60

Update: num-- → 2. The condition moves toward false.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum2factorial60

Condition: 2 > 1 → true → run the body.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum2factorial120

factorial = 60 × 2 = 120.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum1factorial120

Update: num-- → 1. The condition moves toward false.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum1factorial120

Condition: 1 > 1 → false → exit the loop.

num = 5factorial = 1initializationnum > 1conditionfactorial *= numbodynum--updatetruerepeat (to condition)falseprintln(factorial)after the loopnum1factorial120

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 (…);.
initializationint choice;bodyprint menuupdatechoice = nextInt()choice != 0conditiontruefalseprintln("Goodbye")

Loops · Step through the code

Code Trace: a do-while menu (input 1, 2, 0)

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice?in1 2 0

A Scanner reads from the keyboard (import java.util.Scanner; at the top). The user will type 1, 2, 0.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice?in1 2 0

choice is declared without a value; that's fine, since the condition is first tested after the body.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice?in1 2 0

Pass 1: the body runs without checking the condition; the menu is printed.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice1in2 0

The user types 1 → choice = 1.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice1in2 0

choice == 1 → true: «Hello!» is printed.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice1in2 0

Condition: 1 != 0 → true → back to the top.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice1in2 0

Pass 2: the body runs without checking the condition; the menu is printed.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice2in0

The user types 2 → choice = 2.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice2in0

choice == 1 → false: nothing happens.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice2in0

Condition: 2 != 0 → true → back to the top.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice2in0

Pass 3: the body runs without checking the condition; the menu is printed.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice0in—

The user types 0 → choice = 0.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice0in—

choice == 1 → false: nothing happens.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice0in—

Condition: 0 != 0 → false → the loop ends.

int choice;initializationprint("Choice…")if (choice == 1) …bodychoice = nextInt()updatechoice != 0conditiontrue → repeatfalseprintln("Goodbye")after the loopchoice0in—

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

SituationChoice
Count from 1 to n, repeat n timesfor
Process digits until the number is 0while
Show a menu, ask until the input is validdo-while
Add until the user types “0”while / do-while

Each can be rewritten as the others; choose for readability.

Pass countknown in advance?yesfornoMust it runat least once?yesnodo-whilewhile

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.
i <= 10 ?i % 3 == 0 ?i == 8 ?print(i)i++continuebreakend of loop

Branching · Step through the code

Code Trace: break and continue

1i2i3i4i5i6i7i8i9i10i

i = 1: 1 % 3 = 1 → false; 1 == 8 → false. Both checks pass.

1iprinted2i3i4i5i6i7i8i9i10i

1 is printed.

1iprinted2i3i4i5i6i7i8i9i10i

i = 2: 2 % 3 = 2 → false; 2 == 8 → false. Both checks pass.

1iprinted2iprinted3i4i5i6i7i8i9i10i

2 is printed.

1iprinted2iprinted3icontinue4i5i6i7i8i9i10i

i = 3: 3 % 3 == 0 → true → continue: print is skipped, straight to i++.

1iprinted2iprinted3icontinue4i5i6i7i8i9i10i

i = 4: 4 % 3 = 1 → false; 4 == 8 → false. Both checks pass.

1iprinted2iprinted3icontinue4iprinted5i6i7i8i9i10i

4 is printed.

1iprinted2iprinted3icontinue4iprinted5i6i7i8i9i10i

i = 5: 5 % 3 = 2 → false; 5 == 8 → false. Both checks pass.

1iprinted2iprinted3icontinue4iprinted5iprinted6i7i8i9i10i

5 is printed.

1iprinted2iprinted3icontinue4iprinted5iprinted6icontinue7i8i9i10i

i = 6: 6 % 3 == 0 → true → continue: print is skipped, straight to i++.

1iprinted2iprinted3icontinue4iprinted5iprinted6icontinue7i8i9i10i

i = 7: 7 % 3 = 1 → false; 7 == 8 → false. Both checks pass.

1iprinted2iprinted3icontinue4iprinted5iprinted6icontinue7iprinted8i9i10i

7 is printed.

1iprinted2iprinted3icontinue4iprinted5iprinted6icontinue7iprinted8ibreak9i10i

i = 8: 8 % 3 = 2 → false; 8 == 8 → true → break: the loop ends here; 9 and 10 are never reached.

1iprinted2iprinted3icontinue4iprinted5iprinted6icontinue7iprinted8ibreak9i10i

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

-3-2-10123456i < 5target: i ≥ 5i-- : away from the goalfor (int i = 0; i < 5; i--) → i = 0, −1, −2, … always truewhile (i < 5) { … } // no i++ → i stays 0
  • If the condition never becomes false, the loop never ends: the program seems “frozen”.
  • Note: with i-- the int eventually 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 a break condition 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.
1234start of pass: i = 1sum = 0= (empty sum)

No number processed yet: sum = 0 (the empty sum). The invariant holds from the start.

1234start of pass: i = 2sum = 1= 1

At the start of pass i = 2, sum holds 1 … 1 added up: 1.

1234start of pass: i = 3sum = 3= 1 + 2

At the start of pass i = 3, sum holds 1 … 2 added up: 3.

1234start of pass: i = 4sum = 6= 1 + 2 + 3

At the start of pass i = 4, sum holds 1 … 3 added up: 6.

1234start of pass: i = 5sum = 10= 1 + 2 + 3 + 4

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)

for (i = 1; i <= 5; i++)-2-101✓2✓3✓4✓5✓6correct: 5 passesfor (i = 1; i < 5; i++)✓✓✓✓one short: 5 is missedfor (i = 0; i <= 5; i++)!✓✓✓✓✓one extra: 6 passesfor (i = 1; i <= 5; i--)!!!✓…wrong direction: infinite
  • < 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);
restdigits5070/ 10pass 1+1501/ 10pass 2+152/ 10pass 3+103rest > 0 false → stopresult: 3 digits
  • Each / 10 drops 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)

−507num = -507num-507digits–

Let's try a negative number: num = −507.

−507rest = -507num-507digits–

The int is copied into a long (the negation of −2147483648 does not fit in an int, but fits in a long).

507rest = 507num-507digits–

−507 < 0 → true → rest = 507. The sign does not change the digit count.

507rest = 507num-507digits0

Counter digits = 0.

507rest = 507num-507digits1

Body: one digit counted → digits = 1.

507rest = 50num-507digits1

rest = 507 / 10 = 50 (integer division drops the last digit).

507rest = 50num-507digits1

Condition: 50 > 0 → true → repeat.

507rest = 50num-507digits2

Body: one digit counted → digits = 2.

507rest = 5num-507digits2

rest = 50 / 10 = 5 (integer division drops the last digit).

507rest = 5num-507digits2

Condition: 5 > 0 → true → repeat.

507rest = 5num-507digits3

Body: one digit counted → digits = 3.

507rest = 0num-507digits3

rest = 5 / 10 = 0 (integer division drops the last digit).

507rest = 0num-507digits3

Condition: 0 > 0 → false → done.

507rest = 0num-507digits3

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);
rest% 10sum7255+5/ 10722+7/ 1077+14/ 100rest > 0 false → stop7 + 2 + 5 = 14
  • % 10 gives the last digit.
  • / 10 removes 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)

725num = 725sum–

A number with digits 7, 2 and 5: 725.

725rest = 725sum–

A copy to work on: rest = 725.

725rest = 725sum–

725 < 0 → false: the sign stays.

725rest = 725sum0

Accumulator sum = 0.

725rest = 725sum0

Condition: 725 > 0 → true.

725rest = 725% 10 → 5sum5

Last digit 725 % 10 = 5; sum = 0 + 5 = 5.

725rest = 72sum5

rest = 725 / 10 = 72: the processed digit is dropped.

725rest = 72sum5

Condition: 72 > 0 → true.

725rest = 72% 10 → 2sum7

Last digit 72 % 10 = 2; sum = 5 + 2 = 7.

725rest = 7sum7

rest = 72 / 10 = 7: the processed digit is dropped.

725rest = 7sum7

Condition: 7 > 0 → true.

725rest = 7% 10 → 7sum14

Last digit 7 % 10 = 7; sum = 7 + 7 = 14.

725rest = 0sum14

rest = 7 / 10 = 0: the processed digit is dropped.

725rest = 0sum14

Condition: 0 > 0 → false.

725rest = 0sum14

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)

1221num = 1221rev–

A number that reads the same backward is a palindrome. Let's try 1221.

1221rest = 1221rev0

We work on a copy; the reversed number is built up from 0.

1221rest = 1221rev0

Condition: 1221 > 0 → true.

1221rest = 1221% 10 → 1rev1

digit = 1221 % 10 = 1; rev = 0 × 10 + 1 = 1 (earlier digits shift one place left).

1221rest = 122rev1

rest = 1221 / 10 = 122.

1221rest = 122rev1

Condition: 122 > 0 → true.

1221rest = 122% 10 → 2rev12

digit = 122 % 10 = 2; rev = 1 × 10 + 2 = 12 (earlier digits shift one place left).

1221rest = 12rev12

rest = 122 / 10 = 12.

1221rest = 12rev12

Condition: 12 > 0 → true.

1221rest = 12% 10 → 2rev122

digit = 12 % 10 = 2; rev = 12 × 10 + 2 = 122 (earlier digits shift one place left).

1221rest = 1rev122

rest = 12 / 10 = 1.

1221rest = 1rev122

Condition: 1 > 0 → true.

1221rest = 1% 10 → 1rev1221

digit = 1 % 10 = 1; rev = 122 × 10 + 1 = 1221 (earlier digits shift one place left).

1221rest = 0rev1221

rest = 1 / 10 = 0.

1221rest = 0rev1221

Condition: 0 > 0 → false.

1221rest = 0rev1221

The reversed number 1221 is printed.

1221rest = 0rev1221

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³

153num = 153sum–

Armstrong number: equals the sum of its digits each raised to the number of digits. 153 has three digits → cubes.

153rest = 153sum0

rest = 153, sum = 0.

153rest = 153sum0

Condition: 153 > 0 → true.

153rest = 1533³ = 27sum27

r = 3; sum = 0 + 3×3×3 = 27.

153rest = 15sum27

rest /= 10 → 15.

153rest = 15sum27

Condition: 15 > 0 → true.

153rest = 155³ = 125sum152

r = 5; sum = 27 + 5×5×5 = 152.

153rest = 1sum152

rest /= 10 → 1.

153rest = 1sum152

Condition: 1 > 0 → true.

153rest = 11³ = 1sum153

r = 1; sum = 152 + 1×1×1 = 153.

153rest = 0sum153

rest /= 10 → 0.

153rest = 0sum153

Condition: 0 > 0 → false.

153rest = 0sum153

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

1234567891011121314sum = 0

Perfect number: equals the sum of its divisors other than itself (6 = 1 + 2 + 3). Let's try 28.

1234567891011121314sum = 0

The divisor sum starts at 0. Apart from n itself, the largest divisor is at most n / 2 = 14.

1divisor234567891011121314sum = 1

i = 1: 28 % 1 = 0 → divisor, sum = 1.

1divisor2divisor34567891011121314sum = 1 + 2 = 3

i = 2: 28 % 2 = 0 → divisor, sum = 3.

1divisor2divisor34567891011121314sum = 1 + 2 = 3

i = 3: 28 % 3 = 1 → not a divisor.

1divisor2divisor34divisor567891011121314sum = 1 + 2 + 4 = 7

i = 4: 28 % 4 = 0 → divisor, sum = 7.

1divisor2divisor34divisor567891011121314sum = 1 + 2 + 4 = 7

i = 5: 28 % 5 = 3 → not a divisor.

1divisor2divisor34divisor567891011121314sum = 1 + 2 + 4 = 7

i = 6: 28 % 6 = 4 → not a divisor.

1divisor2divisor34divisor567divisor891011121314sum = 1 + 2 + 4 + 7 = 14

i = 7: 28 % 7 = 0 → divisor, sum = 14.

1divisor2divisor34divisor567divisor891011121314sum = 1 + 2 + 4 + 7 = 14

i = 8: 28 % 8 = 4 → not a divisor.

1divisor2divisor34divisor567divisor891011121314sum = 1 + 2 + 4 + 7 = 14

i = 9: 28 % 9 = 1 → not a divisor.

1divisor2divisor34divisor567divisor891011121314sum = 1 + 2 + 4 + 7 = 14

i = 10: 28 % 10 = 8 → not a divisor.

1divisor2divisor34divisor567divisor891011121314sum = 1 + 2 + 4 + 7 = 14

i = 11: 28 % 11 = 6 → not a divisor.

1divisor2divisor34divisor567divisor891011121314sum = 1 + 2 + 4 + 7 = 14

i = 12: 28 % 12 = 4 → not a divisor.

1divisor2divisor34divisor567divisor891011121314sum = 1 + 2 + 4 + 7 = 14

i = 13: 28 % 13 = 2 → not a divisor.

1divisor2divisor34divisor567divisor891011121314divisorsum = 1 + 2 + 4 + 7 + 14 = 28

i = 14: 28 % 14 = 0 → divisor, sum = 28.

1divisor2divisor34divisor567divisor891011121314divisorsum = 1 + 2 + 4 + 7 + 14 = 28

i = 15 <= 14 → false: the loop ends.

1divisor2divisor34divisor567divisor891011121314divisorsum = 1 + 2 + 4 + 7 + 14 = 28

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

divisionremainder (bit)read the bits bottom to topbinary–place–

Converting 13 to binary: divide by 2 repeatedly and collect the remainders.

divisionremainder (bit)read the bits bottom to topbinary0place1

We build the binary result from decimal digits (1s and 0s); place = 1 is the ones place.

divisionremainder (bit)read the bits bottom to topbinary0place1

Condition: 13 > 0 → true.

divisionremainder (bit)13 / 2 = 61← bitread the bits bottom to topbinary1place1

13 % 2 = 1 → bin += 1 × 1 → 1.

divisionremainder (bit)13 / 2 = 61read the bits bottom to topbinary1place10

Next bit is one place left: place = 10; n = n / 2 = 6.

divisionremainder (bit)13 / 2 = 61read the bits bottom to topbinary1place10

Condition: 6 > 0 → true.

divisionremainder (bit)13 / 2 = 616 / 2 = 30← bitread the bits bottom to topbinary1place10

6 % 2 = 0 → bin += 0 × 10 → 1.

divisionremainder (bit)13 / 2 = 616 / 2 = 30read the bits bottom to topbinary1place100

Next bit is one place left: place = 100; n = n / 2 = 3.

divisionremainder (bit)13 / 2 = 616 / 2 = 30read the bits bottom to topbinary1place100

Condition: 3 > 0 → true.

divisionremainder (bit)13 / 2 = 616 / 2 = 303 / 2 = 11← bitread the bits bottom to topbinary101place100

3 % 2 = 1 → bin += 1 × 100 → 101.

divisionremainder (bit)13 / 2 = 616 / 2 = 303 / 2 = 11read the bits bottom to topbinary101place1000

Next bit is one place left: place = 1000; n = n / 2 = 1.

divisionremainder (bit)13 / 2 = 616 / 2 = 303 / 2 = 11read the bits bottom to topbinary101place1000

Condition: 1 > 0 → true.

divisionremainder (bit)13 / 2 = 616 / 2 = 303 / 2 = 111 / 2 = 01← bitread the bits bottom to topbinary1101place1000

1 % 2 = 1 → bin += 1 × 1000 → 1101.

divisionremainder (bit)13 / 2 = 616 / 2 = 303 / 2 = 111 / 2 = 01read the bits bottom to topbinary1101place10000

Next bit is one place left: place = 10000; n = n / 2 = 0.

divisionremainder (bit)13 / 2 = 616 / 2 = 303 / 2 = 111 / 2 = 01read the bits bottom to topbinary1101place10000

Condition: 0 > 0 → false.

divisionremainder (bit)13 / 2 = 616 / 2 = 303 / 2 = 111 / 2 = 01read the bits bottom to topbinary1101place10000

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);
1×2i=02×2i=14×2i=28×2i=316resulti = 4: 4 < 4 false → stop2 × 2 × 2 × 2 = 16
  • 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⁴

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4

We will compute 2⁴: base = 2, exp = 4.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result1

1 is the identity for multiplication: result = 1 (= 2⁰).

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result1i0

Initialization: i = 0. The loop will run exp times (0, 1, 2, 3).

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result1i0

Condition: 0 < 4 → true.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result2i0

result = 1 × 2 = 2 (= 21).

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result2i1

Update: i = 1.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result2i1

Condition: 1 < 4 → true.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result4i1

result = 2 × 2 = 4 (= 22).

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result4i2

Update: i = 2.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result4i2

Condition: 2 < 4 → true.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result8i2

result = 4 × 2 = 8 (= 23).

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result8i3

Update: i = 3.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result8i3

Condition: 3 < 4 → true.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result16i3

result = 8 × 2 = 16 (= 24).

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result16i4

Update: i = 4.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result16i4

Condition: 4 < 4 → false.

int i = 0initializationi < expconditionresult *= basebodyi++updatetruerepeat (to condition)falseprintln(result)after the loopbase2exp4result16

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);
i29 % ii ≤ 29/i212≤14323≤9414≤7545≤56—6≤4false → stopno remainder is 0 → prime = true
  • 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?

2i3i4i5i6idivisor candidatesn29prime?

Is n = 29 prime?

2i3i4i5i6idivisor candidatesn29primetrue

29 >= 2 → true. Assume prime until proven otherwise.

2i29 / 2 = 143i4i5i6idivisor candidatesn29primetrue

Start: the first divisor candidate is i = 2.

2i29 / 2 = 143i4i5i6idivisor candidatesn29primetrue

Condition: true && 2 <= 29/2 = 14 → true.

2i29 % 2 = 13i4i5i6idivisor candidatesn29primetrue

29 % 2 = 1 → not a divisor.

2i29 % 2 = 13i29 / 3 = 94i5i6idivisor candidatesn29primetrue

Update: i = 3.

2i29 % 2 = 13i29 / 3 = 94i5i6idivisor candidatesn29primetrue

Condition: true && 3 <= 29/3 = 9 → true.

2i29 % 2 = 13i29 % 3 = 24i5i6idivisor candidatesn29primetrue

29 % 3 = 2 → not a divisor.

2i29 % 2 = 13i29 % 3 = 24i29 / 4 = 75i6idivisor candidatesn29primetrue

Update: i = 4.

2i29 % 2 = 13i29 % 3 = 24i29 / 4 = 75i6idivisor candidatesn29primetrue

Condition: true && 4 <= 29/4 = 7 → true.

2i29 % 2 = 13i29 % 3 = 24i29 % 4 = 15i6idivisor candidatesn29primetrue

29 % 4 = 1 → not a divisor.

2i29 % 2 = 13i29 % 3 = 24i29 % 4 = 15i29 / 5 = 56idivisor candidatesn29primetrue

Update: i = 5.

2i29 % 2 = 13i29 % 3 = 24i29 % 4 = 15i29 / 5 = 56idivisor candidatesn29primetrue

Condition: true && 5 <= 29/5 = 5 → true.

2i29 % 2 = 13i29 % 3 = 24i29 % 4 = 15i29 % 5 = 46idivisor candidatesn29primetrue

29 % 5 = 4 → not a divisor.

2i29 % 2 = 13i29 % 3 = 24i29 % 4 = 15i29 % 5 = 46i29 / 6 = 4divisor candidatesn29primetrue

Update: i = 6.

2i29 % 2 = 13i29 % 3 = 24i29 % 4 = 15i29 % 5 = 46idivisor candidatesn29primetrue

Condition: true && 6 <= 29/6 = 4 → false: we are past √29, so no larger divisor needs checking.

2i29 % 2 = 13i29 % 3 = 24i29 % 4 = 15i29 % 5 = 46idivisor candidatesn29primetrue

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?

2i3i4i5i6idivisor candidatesn21prime?

Is n = 21 prime?

2i3i4i5i6idivisor candidatesn21primetrue

21 >= 2 → true. Assume prime until proven otherwise.

2i21 / 2 = 103i4i5i6idivisor candidatesn21primetrue

Start: the first divisor candidate is i = 2.

2i21 / 2 = 103i4i5i6idivisor candidatesn21primetrue

Condition: true && 2 <= 21/2 = 10 → true.

2i21 % 2 = 13i4i5i6idivisor candidatesn21primetrue

21 % 2 = 1 → not a divisor.

2i21 % 2 = 13i21 / 3 = 74i5i6idivisor candidatesn21primetrue

Update: i = 3.

2i21 % 2 = 13i21 / 3 = 74i5i6idivisor candidatesn21primetrue

Condition: true && 3 <= 21/3 = 7 → true.

2i21 % 2 = 13i21 % 3 = 04i5i6idivisor candidatesn21primefalse

21 % 3 = 0 → divisor found: prime = false.

2i21 % 2 = 13i21 % 3 = 04i5i6idivisor candidatesn21primefalse

Update: i = 4.

2i21 % 2 = 13i21 % 3 = 04i5i6idivisor candidatesn21primefalse

Condition: prime = false → && short-circuits, i <= n / i is never evaluated → the loop ends.

2i21 % 2 = 13i21 % 3 = 04i5i6idivisor candidatesn21primefalse

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)

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

For each k from 2 to 20, a primality test (inner loop) runs.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 2: inner loop never runs (2 > k / 2) → prime = true → printed.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 3: inner loop never runs (2 > k / 2) → prime = true → printed.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 4: 4 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 5: no divisor in 2 … 2 → prime = true → printed.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 6: 6 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 7: no divisor in 2 … 2 → prime = true → printed.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 8: 8 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 9: 9 % 3 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 10: 10 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 11: no divisor in 2 … 3 → prime = true → printed.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 12: 12 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 13: no divisor in 2 … 3 → prime = true → printed.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 14: 14 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 15: 15 % 3 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 16: 16 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 17: no divisor in 2 … 4 → prime = true → printed.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 18: 18 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 19: no divisor in 2 … 4 → prime = true → printed.

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

k = 20: 20 % 2 = 0 → prime = false, break (the inner loop ends early).

234567891011121314151617181920green = prime, faded = composite, dashed = not checked yet

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;
}
a (printed)bi=00112358i=10112358i=20112358i=30112358i=40112358output: 0 1 1 2 3
  • 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 = next first 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

printed sequencea–b–next–

We will print the first 5 Fibonacci numbers.

printed sequencea0b1next–

The first two terms: a = 0, b = 1.

0printed sequencea0b1next–

i = 0 < 5 → true. Print the next term, a = 0.

0printed sequencea0b1next1

next = 0 + 1 = 1.

0printed sequencea ← b ← nexta1b1next1

Shift: a = 1, b = 1. Order matters: a = b first, then b = next. Then i++.

01printed sequencea1b1next–

i = 1 < 5 → true. Print the next term, a = 1.

01printed sequencea1b1next2

next = 1 + 1 = 2.

01printed sequencea ← b ← nexta1b2next2

Shift: a = 1, b = 2. Order matters: a = b first, then b = next. Then i++.

011printed sequencea1b2next–

i = 2 < 5 → true. Print the next term, a = 1.

011printed sequencea1b2next3

next = 1 + 2 = 3.

011printed sequencea ← b ← nexta2b3next3

Shift: a = 2, b = 3. Order matters: a = b first, then b = next. Then i++.

0112printed sequencea2b3next–

i = 3 < 5 → true. Print the next term, a = 2.

0112printed sequencea2b3next5

next = 2 + 3 = 5.

0112printed sequencea ← b ← nexta3b5next5

Shift: a = 3, b = 5. Order matters: a = b first, then b = next. Then i++.

01123printed sequencea3b5next–

i = 4 < 5 → true. Print the next term, a = 3.

01123printed sequencea3b5next8

next = 3 + 5 = 8.

01123printed sequencea ← b ← nexta5b8next8

Shift: a = 5, b = 8. Order matters: a = b first, then b = next. Then i++.

01123printed sequencea5b8next–

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)

1255075100possible range 1..100

Random generates random numbers (import java.util.Random; and java.util.Scanner at the top).

1255075100possible range 1..100

A Scanner to read from the keyboard.

1255075100possible range 1..100target = 37 (hidden)

nextInt(100) gives 0..99; +1 makes it 1..100. This run picked target = 37 (it differs every run).

1255075100possible range 1..100target = 37 (hidden)

guess = 0 can never be the target → the loop is sure to start.

1255075100possible range 1..100target = 37 (hidden)

Condition: 0 != 37 → true.

1255075100possible range 1..100guess 50target = 37 (hidden)

The user types 50; tries = 1.

1255075100possible range 1..49guess 50target = 37 (hidden)

50 > 37 → «Lower». Possible range 1..49. Guessing the middle each time halves the range.

1255075100possible range 1..49guess 50target = 37 (hidden)

Condition: 50 != 37 → true.

1255075100possible range 1..49guess 25target = 37 (hidden)

The user types 25; tries = 2.

1255075100possible range 26..49guess 25target = 37 (hidden)

25 < 37 → «Higher». Possible range 26..49.

1255075100possible range 26..49guess 25target = 37 (hidden)

Condition: 25 != 37 → true.

1255075100possible range 26..49guess 37target = 37 (hidden)

The user types 37; tries = 3.

1255075100possible range 37..37guess 37target = 37 (hidden)

37 is neither smaller nor larger: both ifs are false, no message.

1255075100possible range 37..37guess 37target = 37 (hidden)

Condition: 37 != 37 → false → the loop ends.

1255075100possible range 37..37guess 37target = 37 (hidden)

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();
}
col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2(2,0)(2,1)(2,2)(2,3)outer loop →picks the rowinner loop →visits the cells
  • 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

col 0col 1col 2col 3row 0(0,0)row 1row 2outer loop →picks the rowinner loop →visits the cells

Outer loop row = 0; the inner loop starts at col = 0 → (0,0).

col 0col 1col 2col 3row 0(0,0)(0,1)row 1row 2outer loop →picks the rowinner loop →visits the cells

col++ → 1 < 4 → true → (0,1) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)row 1row 2outer loop →picks the rowinner loop →visits the cells

col++ → 2 < 4 → true → (0,2) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1row 2outer loop →picks the rowinner loop →visits the cells

col++ → 3 < 4 → true → (0,3) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1row 2outer loop →picks the rowinner loop →visits the cells

col = 4 < 4 → false: the inner loop is done. println ends the line.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)row 2outer loop →picks the rowinner loop →visits the cells

row++ → row = 1; the inner loop restarts at col = 0.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)row 2outer loop →picks the rowinner loop →visits the cells

col++ → 1 < 4 → true → (1,1) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)row 2outer loop →picks the rowinner loop →visits the cells

col++ → 2 < 4 → true → (1,2) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2outer loop →picks the rowinner loop →visits the cells

col++ → 3 < 4 → true → (1,3) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2outer loop →picks the rowinner loop →visits the cells

col = 4 < 4 → false: the inner loop is done. println ends the line.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2(2,0)outer loop →picks the rowinner loop →visits the cells

row++ → row = 2; the inner loop restarts at col = 0.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2(2,0)(2,1)outer loop →picks the rowinner loop →visits the cells

col++ → 1 < 4 → true → (2,1) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2(2,0)(2,1)(2,2)outer loop →picks the rowinner loop →visits the cells

col++ → 2 < 4 → true → (2,2) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2(2,0)(2,1)(2,2)(2,3)outer loop →picks the rowinner loop →visits the cells

col++ → 3 < 4 → true → (2,3) is printed.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2(2,0)(2,1)(2,2)(2,3)outer loop →picks the rowinner loop →visits the cells

col = 4 < 4 → false: the inner loop is done. println ends the line.

col 0col 1col 2col 3row 0(0,0)(0,1)(0,2)(0,3)row 1(1,0)(1,1)(1,2)(1,3)row 2(2,0)(2,1)(2,2)(2,3)outer loop →picks the rowinner loop →visits the cells

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)

i \ jj = 1j = 2j = 3i = 11×1=1i = 2i = 3cell (i, j) = i × j%4d: width of 4 characters

Outer loop i = 1; inner loop starts at j = 1: 1 × 1 = 1.

i \ jj = 1j = 2j = 3i = 111×2=2i = 2i = 3cell (i, j) = i × j%4d: width of 4 characters

j = 2: 1 × 2 = 2, right-aligned in a 4-character field.

i \ jj = 1j = 2j = 3i = 1121×3=3i = 2i = 3cell (i, j) = i × j%4d: width of 4 characters

j = 3: 1 × 3 = 3, right-aligned in a 4-character field.

i \ jj = 1j = 2j = 3i = 1123i = 2i = 3cell (i, j) = i × j%4d: width of 4 characters

j = 4 <= 3 → false; println ends the line.

i \ jj = 1j = 2j = 3i = 1123i = 22×1=2i = 3cell (i, j) = i × j%4d: width of 4 characters

Outer loop i = 2; inner loop starts at j = 1: 2 × 1 = 2.

i \ jj = 1j = 2j = 3i = 1123i = 222×2=4i = 3cell (i, j) = i × j%4d: width of 4 characters

j = 2: 2 × 2 = 4, right-aligned in a 4-character field.

i \ jj = 1j = 2j = 3i = 1123i = 2242×3=6i = 3cell (i, j) = i × j%4d: width of 4 characters

j = 3: 2 × 3 = 6, right-aligned in a 4-character field.

i \ jj = 1j = 2j = 3i = 1123i = 2246i = 3cell (i, j) = i × j%4d: width of 4 characters

j = 4 <= 3 → false; println ends the line.

i \ jj = 1j = 2j = 3i = 1123i = 2246i = 33×1=3cell (i, j) = i × j%4d: width of 4 characters

Outer loop i = 3; inner loop starts at j = 1: 3 × 1 = 3.

i \ jj = 1j = 2j = 3i = 1123i = 2246i = 333×2=6cell (i, j) = i × j%4d: width of 4 characters

j = 2: 3 × 2 = 6, right-aligned in a 4-character field.

i \ jj = 1j = 2j = 3i = 1123i = 2246i = 3363×3=9cell (i, j) = i × j%4d: width of 4 characters

j = 3: 3 × 3 = 9, right-aligned in a 4-character field.

i \ jj = 1j = 2j = 3i = 1123i = 2246i = 3369cell (i, j) = i × j%4d: width of 4 characters

j = 4 <= 3 → false; println ends the line.

i \ jj = 1j = 2j = 3i = 1123i = 2246i = 3369cell (i, j) = i × j%4d: width of 4 characters

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

  1. Draw the expected output for a small n (e.g. 4) on grid paper.
  2. Tabulate how many spaces and how many characters each row has.
  3. Relate the counts to the row number (3, 2, 1, 0 → n − row).
  4. Outer loop = row; one inner loop per part.
1234spacesstarsrow 1···*31row 2··**22row 3·***13row 4****04n − rowrow

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.
1234row 1*row 2**row 3***row 4****

Examples · Step through the code

Code Trace: growing triangle (n = 4)

1234row 1row 2row 3row 4· = spaceorange = cursor

A triangle of n = 4 rows. Each grid cell is one character.

1234row 1*row 2row 3row 4· = spaceorange = cursor

row = 1: inner loop col = 1 … 1 → 1 star(s) on this row.

1234row 1*row 2row 3row 4· = spaceorange = cursor

col = 2 <= 1 → false. println moves to the next line.

1234row 1*row 2*row 3row 4· = spaceorange = cursor

row = 2: inner loop col = 1 … 2 → 2 star(s) on this row.

1234row 1*row 2**row 3row 4· = spaceorange = cursor

col = 2 <= 2 → true → *

1234row 1*row 2**row 3row 4· = spaceorange = cursor

col = 3 <= 2 → false. println moves to the next line.

1234row 1*row 2**row 3*row 4· = spaceorange = cursor

row = 3: inner loop col = 1 … 3 → 3 star(s) on this row.

1234row 1*row 2**row 3**row 4· = spaceorange = cursor

col = 2 <= 3 → true → *

1234row 1*row 2**row 3***row 4· = spaceorange = cursor

col = 3 <= 3 → true → *

1234row 1*row 2**row 3***row 4· = spaceorange = cursor

col = 4 <= 3 → false. println moves to the next line.

1234row 1*row 2**row 3***row 4*· = spaceorange = cursor

row = 4: inner loop col = 1 … 4 → 4 star(s) on this row.

1234row 1*row 2**row 3***row 4**· = spaceorange = cursor

col = 2 <= 4 → true → *

1234row 1*row 2**row 3***row 4***· = spaceorange = cursor

col = 3 <= 4 → true → *

1234row 1*row 2**row 3***row 4****· = spaceorange = cursor

col = 4 <= 4 → true → *

1234row 1*row 2**row 3***row 4****· = spaceorange = cursor

col = 5 <= 4 → false. println moves to the next line.

1234row 1*row 2**row 3***row 4****· = spaceorange = cursor

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.
123row 1··*row 2·**row 3***

Examples · Step through the code

Code Trace: right-aligned triangle (n = 3)

123row 1row 2row 3· = spaceorange = cursor

n = 3. Each row: first n - row spaces, then row stars.

123row 1·row 2row 3· = spaceorange = cursor

row = 1: 2 spaces needed. space = 0 → ' ' is printed.

123row 1··row 2row 3· = spaceorange = cursor

space = 1 < 2 → ' ' is printed.

123row 1··*row 2row 3· = spaceorange = cursor

Spaces done; 1 star(s): star = 0 → *

123row 1··*row 2row 3· = spaceorange = cursor

Row complete (every row has n = 3 characters): println.

123row 1··*row 2·row 3· = spaceorange = cursor

row = 2: 1 space needed. space = 0 → ' ' is printed.

123row 1··*row 2·*row 3· = spaceorange = cursor

Spaces done; 2 star(s): star = 0 → *

123row 1··*row 2·**row 3· = spaceorange = cursor

star = 1 < 2 → *

123row 1··*row 2·**row 3· = spaceorange = cursor

Row complete (every row has n = 3 characters): println.

123row 1··*row 2·**row 3· = spaceorange = cursor

row = 3: space < 3 − 3 = 0 → false: no spaces on this row.

123row 1··*row 2·**row 3*· = spaceorange = cursor

Spaces done; 3 star(s): star = 0 → *

123row 1··*row 2·**row 3**· = spaceorange = cursor

star = 1 < 3 → *

123row 1··*row 2·**row 3***· = spaceorange = cursor

star = 2 < 3 → *

123row 1··*row 2·**row 3***· = spaceorange = cursor

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

PatternSpacesCharacters
Growing triangle0row
Shrinking triangle0n - row + 1
Right-alignedn - rowrow
Pyramidn - row2 × row - 1
**********Growing triangle**********Shrinking triangle**********Right-aligned****************Pyramidn = 4 · dashed square: space, filled square: character

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.
1234row 11row 212row 3123row 41234

Examples · Step through the code

Code Trace: number triangle (n = 4)

1234row 1row 2row 3row 4· = spaceorange = cursor

Each cell gets one value + " " (number and space).

1234row 11row 2row 3row 4· = spaceorange = cursor

row = 1: value runs 1 to 1. value = 1 → “1 ”

1234row 11row 2row 3row 4· = spaceorange = cursor

value = 2 <= 1 → false; println.

1234row 11row 21row 3row 4· = spaceorange = cursor

row = 2: value runs 1 to 2. value = 1 → “1 ”

1234row 11row 212row 3row 4· = spaceorange = cursor

value = 2 → “2 ” (the printed number is the inner loop variable).

1234row 11row 212row 3row 4· = spaceorange = cursor

value = 3 <= 2 → false; println.

1234row 11row 212row 31row 4· = spaceorange = cursor

row = 3: value runs 1 to 3. value = 1 → “1 ”

1234row 11row 212row 312row 4· = spaceorange = cursor

value = 2 → “2 ” (the printed number is the inner loop variable).

1234row 11row 212row 3123row 4· = spaceorange = cursor

value = 3 → “3 ” (the printed number is the inner loop variable).

1234row 11row 212row 3123row 4· = spaceorange = cursor

value = 4 <= 3 → false; println.

1234row 11row 212row 3123row 41· = spaceorange = cursor

row = 4: value runs 1 to 4. value = 1 → “1 ”

1234row 11row 212row 3123row 412· = spaceorange = cursor

value = 2 → “2 ” (the printed number is the inner loop variable).

1234row 11row 212row 3123row 4123· = spaceorange = cursor

value = 3 → “3 ” (the printed number is the inner loop variable).

1234row 11row 212row 3123row 41234· = spaceorange = cursor

value = 4 → “4 ” (the printed number is the inner loop variable).

1234row 11row 212row 3123row 41234· = spaceorange = cursor

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.
0123i = 0****i = 1*··*i = 2*··*i = 3****

Examples · Step through the code

Code Trace: hollow square (n = 4)

0123i = 0i = 1i = 2i = 3· = spaceorange = cursor

n = 4. Edge: first/last row (i = 0, 3) or first/last column (j = 0, 3).

0123i = 0*i = 1i = 2i = 3· = spaceorange = cursor

i = 0, j = 0: i == 0 → true → *

0123i = 0**i = 1i = 2i = 3· = spaceorange = cursor

i = 0, j = 1: i == 0 → true → *

0123i = 0***i = 1i = 2i = 3· = spaceorange = cursor

i = 0, j = 2: i == 0 → true → *

0123i = 0****i = 1i = 2i = 3· = spaceorange = cursor

i = 0, j = 3: i == 0 → true → *

0123i = 0****i = 1i = 2i = 3· = spaceorange = cursor

j = 4 < 4 → false; println.

0123i = 0****i = 1*i = 2i = 3· = spaceorange = cursor

i = 1, j = 0: j == 0 → true → *

0123i = 0****i = 1*·i = 2i = 3· = spaceorange = cursor

i = 1, j = 1: all four conditions false → else → space

0123i = 0****i = 1*··i = 2i = 3· = spaceorange = cursor

i = 1, j = 2: all four conditions false → else → space

0123i = 0****i = 1*··*i = 2i = 3· = spaceorange = cursor

i = 1, j = 3: j == 3 → true → *

0123i = 0****i = 1*··*i = 2i = 3· = spaceorange = cursor

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

0123i = 0****i = 1*··*i = 2*i = 3· = spaceorange = cursor

i = 2, j = 0: j == 0 → true → *

0123i = 0****i = 1*··*i = 2*·i = 3· = spaceorange = cursor

i = 2, j = 1: all four conditions false → else → space

0123i = 0****i = 1*··*i = 2*··i = 3· = spaceorange = cursor

i = 2, j = 2: all four conditions false → else → space

0123i = 0****i = 1*··*i = 2*··*i = 3· = spaceorange = cursor

i = 2, j = 3: j == 3 → true → *

0123i = 0****i = 1*··*i = 2*··*i = 3· = spaceorange = cursor

j = 4 < 4 → false; println.

0123i = 0****i = 1*··*i = 2*··*i = 3*· = spaceorange = cursor

i = 3, j = 0: i == 3 → true → *

0123i = 0****i = 1*··*i = 2*··*i = 3**· = spaceorange = cursor

i = 3, j = 1: i == 3 → true → *

0123i = 0****i = 1*··*i = 2*··*i = 3***· = spaceorange = cursor

i = 3, j = 2: i == 3 → true → *

0123i = 0****i = 1*··*i = 2*··*i = 3****· = spaceorange = cursor

i = 3, j = 3: i == 3 → true → *

0123i = 0****i = 1*··*i = 2*··*i = 3****· = spaceorange = cursor

j = 4 < 4 → false; println.

0123i = 0****i = 1*··*i = 2*··*i = 3****· = spaceorange = cursor

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.
correct******println in inner loop******

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 testnumberexpected
Normal40964
Zero01
Negative−5073
Extreme−214748364810

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

  1. What is the key difference between while and do-while?
  2. What do break and continue do?
  3. What are % 10 and / 10 for in the sum of digits?
  4. Why is the inner loop's upper bound the row variable in the growing triangle?
  5. How does the output change if println is inside the inner loop?

Summary

Exercises

  1. Read numbers until 0 is entered and print their sum and average (while).
  2. Find the sum of the numbers from 1 to 100 divisible by 3 or 5 (answer: 2418).
  3. Draw an n-row pyramid: row r has n − r spaces and 2r − 1 stars (trace it by hand for n = 4).
  4. Compute the factorial of a number with for; why doesn't 13! fit in an int? Try long.
  5. Use do-while to keep asking until the user enters a score from 1 to 5.
  6. 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).

The End

Chapter 8: Loops
Previous: Chapter 7: Conditionals · Next: Chapter 9: Methods
1 / 1Sercan KÜLCÜ. All rights reserved.