Skip to content

Information Technology · Ch 2 — Introduction to Programming

Control Structures — Looping

5

Control Structures — Looping

A loop (iteration) repeats a block of statements as long as a condition remains true. Loops save us from writing the same code many times — printing 1 to 100 needs one loop, not a hundred statements.

Every loop needs three things: an initialisation (a starting value), a condition (when to keep going) and an update (how the value changes each time), or it will never stop — an infinite loop.

The while loop

Tests the condition before each repetition, so the body may run zero times:

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;                 // update — without this the loop never ends
}

The do...while loop

Tests the condition after the body, so the body always runs at least once:

int n = 1;
do {
    System.out.println(n);
    n++;
} while (n <= 5);

The for loop

Puts initialisation, condition and update on one line — ideal when the number of repetitions is known:

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Nested loops

A loop inside another loop is used for tables and patterns; the inner loop completes fully for each single pass of the outer loop:

for (int r = 1; r <= 3; r++) {
    for (int c = 1; c <= 3; c++) {
        System.out.print(r * c + "\t");
    }
    System.out.println();     // new line after each row
}

break and continue

  • break exits the loop immediately. …
Definition 1Loop / iteration

A control structure that repeats a block of statements while a condition …

Definition 2while loop

A loop that checks its condition before each pass, so its body may ru …

Definition 3do-while loop

A loop that checks its condition after the body, so the body always runs …

Definition 4for loop

A loop that combines initialisation, condition and update on one line; best when the number of rep …

Definition 5break / continue

break exits a loop immediately; continue skips to the next repetition …

Definition 6Infinite loop

A loop whose condition never becomes false — usually because the update step is missing — so …