Skip to the workspace
Pebellslearn by building
Control Flow  ›  Lesson

for, while and do-while

for / while / do while loops 14 minA for loop suits a known count, a while loop repeats as long as a condition holds and may never run, and a do-while loop runs its body once before checking.

c / for, while and do-while

Explore each scene at your own pace.

01 · The rule

The rule

for, while and do-while

A for loop suits a known count, a while loop repeats as long as a condition holds and may never run, and a do-while loop runs its body once before checking.

Trace initialization, condition checks and updates, including an empty iteration.

The logger now repeats itself all day long: add up 24 hourly readings, wait until the sensor is ready, show a settings menu at least once. C has three loops, and each one matches one of these jobs. Pick the matching loop and most off-by-one bugs never get written.

The rule

for counts, while waits, do-while acts once before asking.

for puts the start, the test and the step on one line. It is the natural fit when you know how many times to repeat:

int hourly[24] = {0};   /* filled in by the sensor code */
long total = 0;

for (int h = 0; h < 24; h++) {
    total += hourly[h];
}

The order is: run int h = 0 once; test h < 24; if true, run the body, then h++, and test again. A variable declared in the first part (C99 and later) exists only inside the loop.

while tests first and repeats as long as the condition holds. If the condition is false at the start, the body never runs:

while (!sensor_ready()) {
    /* keep waiting */
}

do … while runs the body first and tests afterwards, so the body always runs at least once. Note the semicolon at the end:

int choice;
do {
    choice = show_menu();
} while (choice != 0);

for (;;) with every part empty is the conventional "loop forever"; embedded programs often wrap their whole main job in one. The greenhouse board does exactly that: read the sensor, log the value, wait a minute, repeat until the power goes off.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.