Skip to main content

do...while versus for/while loops

Short answer

do...while is exit‑controlled, so its body runs at least once; for loop is entry‑controlled with initialisation, condition, and update in one header, typically used when the iteration count is known. do alone is just the keyword; the full construct is do { ... } while (condition).

Differentiate between do...while and for statements. Write the difference between do and do...while loop.

do...while versus for

do...whilefor
Exit-controlled: condition is tested after the bodyEntry-controlled: condition is tested before the body
Body executes at least onceBody may not execute at all
Initialisation and update are written separatelyInitialisation, condition and update are in one line
Semicolon is needed after while(condition);No semicolon after the header
Used when the number of repetitions is not known and at least one run is needed (menus)Used when the number of repetitions is known

do versus do...while

do is only the keyword that starts the loop; it cannot be used alone. The complete loop is do { ... } while (condition);, where do starts the body and the while clause at the end decides whether to repeat. The (entry-controlled) while loop tests first; the do...while loop tests after the body.

#include <stdio.h>
int main(void)
{
    int i = 10;
    while (i < 5)
        printf("while body runs: %d\n", i);
    do
    {
        printf("do-while body runs once: %d\n", i);
    } while (i < 5);
    for (i = 1; i <= 3; i++)
        printf("for: %d\n", i);
    return 0;
}

Output:

do-while body runs once: 10
for: 1
for: 2
for: 3

The while loop did not run (10 < 5 is false), but do...while ran once.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →