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.4 Iteration — the for loop

Lesson

The for loop

A for loop packs the three counter parts onto one line: for (start; condition; update). It does the same job as a counted while, just more compactly.


Worked example

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

Start i = 1; check i <= 3 before each pass; run the body; then do i++. Output is 1, 2, 3.


▶ Try it: run this, then change i <= 5 to a different limit, or i++ to i += 2, and re-run.



How many times does this loop run?

for (int i = 0; i < 4; i++) {
    System.out.println("*");
}

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

for (int i = 5; i > 0; i--) {
    System.out.println(i);
}

In for (int i = 0; i < n; i++), click the part that is the condition.


What does this print?

for (int i = 2; i <= 10; i += 2) {
    System.out.print(i + " ");
}

Assemble a for loop that prints the numbers 1 to n.