Skip to the task
Layout
Back to classic view

You are looking at lesson 3. Your place is still Practice test 1, task 1: About.

READTask 2 of 22 · step 2: Loops: while, do-while and for

Loops: while, do-while and for

while, do-while and for, break and continue, and what to do when a loop never ends.

while

int i = 1;
while (i <= 3) {
    printf("%d\n", i);
    i++;
}

While the condition is true, the body { } repeats. The condition is checked before each time, so if it is false from the start, the body doesn't run even once. i++ increases i by one: the same as i = i + 1.

i = 1i <= 3?printf, i++next yesnoback to the condition

do-while

int grade;
do {
    grade = read_int("Grade: ");
} while (grade < 1 || grade > 10);

The condition is checked after the body, so the body runs at least once. It fits when you always have to ask, and repeat only if the answer doesn't fit. The ; after while (...) at the end is required.

for

for (int i = 1; i <= 3; i++) {
    printf("%d\n", i);
}

for puts three parts in one line: the start (int i = 1), the condition (i <= 3) and the step (i++). It does the same as the while above. Use it when you know in advance how many times to repeat.

  • i += 3 is the same as i = i + 3. There are also -=, *= and /=, and i-- decreases by one.
  • An int i declared inside for exists only inside the loop. A variable declared inside { } exists until those braces end.

break and continue

  • break ends the loop at once.
  • continue skips the rest of the body and goes on to the next time round.

A loop without an end

If the condition never becomes false, the loop spins forever. Most often an i++ is forgotten, or reading a new value inside the loop. In CLion you stop such a program with the red square ■ (Ctrl+F2). On GitHub a time limit cuts the test off after a few seconds.