4.1.1.2 - Definite, indefinite and nested iteration (Java)

4.1.1.2 - Definite, indefinite and nested iteration (Java)

Choose count-controlled, pre-test and post-test Java loops, then trace how nested loops change state and terminate.

Java route status: incomplete: runnable support pending. All code answers here are written practice.

Count-controlled loops

Definite iteration repeats a body a known number of times, commonly using a counter.

Iteration

Repeated execution of a group of statements, controlled by a count or a condition.

Java
int total = 0;
for (int number = 1; number <= 4; number++) {
    total = total + number;
}
System.out.println(total);

In a for statement, initialisation happens once. The condition is tested before each repetition. If true, the body runs and then the update runs; control returns to the condition. If false, execution continues after the loop. The body sees number values 1, 2, 3, 4; totals become 1, 3, 6, 10. The final test at 5 is false, so the output is 10.

The counter is declared in the loop header and is in scope there and in its body. total must be declared before the loop so it can accumulate across repetitions and be used afterward. Initialising total = 0 inside the body would erase previous additions. Starting at zero and using < 4 is another way to obtain four iterations, but it visits 0, 1, 2, 3: the visited values, not just the iteration count, must meet the requirement.

Meaningful names clarify the role of each state variable. A count-controlled loop can contain assignments, selection and method calls; sequence still governs the order inside each iteration.

Pre-test and post-test loops

Indefinite iteration repeats until a condition changes, rather than fixing the number of repetitions in advance.

Java while is a pre-test loop: the condition is checked before the body, so the body may execute zero times. Java do ... while is a post-test loop: the body runs before the check and therefore executes at least once. In both Java forms a true condition means continue. A pseudocode REPEAT ... UNTIL finished instead continues while its stopping condition is false; translating it requires negating that condition.

Java
int balance = 12;
while (balance >= 5) {
    balance -= 5;
}
System.out.println(balance);

The balance becomes 7 then 2; the output is 2. If it began at 3, the body would not run. A post-test version with the same condition would subtract once from 3 and leave -2. This is a change in behaviour, not just a spelling change.

A first input must be read before a pre-test sentinel loop can test it. A sentinel is a special value meaning stop, such as -1 when valid readings are non-negative. Do not add the sentinel to the data total. A post-test loop fits asking for an initial answer that must happen once:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int rating;
        do {
            System.out.println("Rating 1 to 5:");
            rating = keyboard.nextInt();
        } while (rating < 1 || rating > 5);
        System.out.println("Accepted " + rating);
    }
}

This example assumes inputs are integers; exception handling for text is taught later. Inputs 0, 6, 4 cause three prompts, then Accepted 4. Every loop needs progress toward a false continuation condition: reading a fresh rating supplies that progress. Testing an unchanged invalid rating forever would create an infinite loop.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account