Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

2.3 Iteration — the counter and stopping

Lesson

Counter and termination

Most while loops use a counter variable: start it, test it in the condition, and update it inside the body. If the body never moves the counter toward making the condition false, the loop runs forever — an infinite loop.


Worked example

int i = 0;
while (i < 3) {
    System.out.println("hi");
    i++;          // without this line, the loop never ends
}

The three parts: start (i = 0), test (i < 3), update (i++).


▶ Try it: run this (it steps by 2). Now change i += 2 to i += 1 or i += 3 and re-run — the update controls how the counter moves and when the loop stops.



What happens if the i++ line is removed?

int i = 0;
while (i < 3) {
    System.out.println("hi");
}

Click the part that updates the counter (the update step).


How many times does the body run?

int i = 2;
while (i <= 6) {
    // body
    i++;
}

Sort each loop by whether it ends or runs forever. Assume the body only prints.


True or false?


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    int i = 0;
    while (i < 3) {
        System.out.println(i);
        i++;
    }
}}