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.4 Iteration — for is a compact while

Lesson

for and while do the same job

A counted for is just a while with the three parts gathered onto one line. Both run the body the same number of times.


Worked example — the same loop, two ways

// for
for (int i = 0; i < n; i++) {
    body;
}

// equivalent while
int i = 0;
while (i < n) {
    body;
    i++;
}

▶ Try it: run this — it counts the even numbers from 1 to 10 (there are 5). Change the 10 and re-run.



Which while loop matches for (int i = 0; i < n; i++) { body }?


Match each for loop to how many times its body runs.


True or false?


Order the parts as they appear in a for-loop header: for ( _ ; _ ; _ ).


Type exactly what this program prints.

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