devnotes.

Loops: for, while, and do...while

C has three loop constructs, each best suited to a different situation.

for (int i = 0; i < 5; i++) {
    printf("%d ", i);
}

int n = 5;
while (n > 0) {
    printf("%d ", n);
    n--;
}

int choice;
do {
    printf("Enter 1 to continue, 0 to stop: ");
    scanf("%d", &choice);
} while (choice != 0);

for bundles initialization, condition, and increment into one line, making it the natural choice when the number of iterations is known ahead of time. while checks its condition before each iteration, so its body may run zero times. do...while checks its condition after each iteration, guaranteeing the body runs at least once — the standard pattern for input-validation loops like the menu example above, where you need to ask at least once before checking whether to stop.

break exits a loop entirely, and continue skips to the next iteration without running the rest of the current one. Be careful with loop conditions that depend on floating-point comparisons for equality (while (x != 1.0)) — accumulated floating-point rounding error can make a loop run one iteration too many or too few, so integer-based loop counters are almost always safer.

C Loops: for, while, and do...while | DevNotes