Loops: while, do-while and for
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.
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 += 3is the same asi = i + 3. There are also-=,*=and/=, andi--decreases by one.- An
int ideclared insideforexists only inside the loop. A variable declared inside{ }exists until those braces end.
break and continue
breakends the loop at once.continueskips 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.