Task 1 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 while loop

Lesson

Iteration: repeating work

A while loop repeats its body as long as a condition stays true. Before each pass it checks the condition; when the condition becomes false, the loop ends and the program continues after it.


Worked example

int i = 1;
while (i <= 3) {
    System.out.println(i);
    i++;
}

Check 1 <= 3 (print 1), 2 <= 3 (print 2), 3 <= 3 (print 3), then 4 <= 3 is false — stop. Output is 1, 2, 3 on three lines.


▶ Try it: run this, then change 5 to a bigger or smaller number — the loop prints that many lines.



How many lines does this print?

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

Type exactly what this prints (each number on its own line):

int n = 5;
while (n > 0) {
    System.out.println(n);
    n--;
}

How many times does the body run?

int i = 1;
while (i <= 5) {
    // body
    i++;
}

True or false?


Assemble a while loop that prints hi three times.