while Loop in C
while repeats a block while its condition stays nonzero, testing before each pass — including the first, so the body may run zero times. It fits open-ended repetition with unknown endpoints: reading until EOF, waiting for valid input, draining queues.
The update lives inside the body, so forgetting it builds an infinite loop — the most common while bug. Structure input as while ((c = getchar()) != EOF) so failed reads end things by themselves.
Test-first repetition
while (n > 0) checks before every iteration — starting at 0 means zero passes, unlike do-while.
Update inside the body
Something must move toward termination, or the loop never ends — the update is the whole termination argument.
Stream conditions
while ((c = getchar()) != EOF) loops over all input and stops cleanly — the idiomatic C input loop.
Zero-trip awareness
Empty input, already-satisfied goals, and failed first reads all skip the body — initialize results for that case.
#include <stdio.h> int main(void) { int n = 5; int fact = 1; while (n > 1) { fact *= n; --n; } printf("%d\n", fact); return 0;}Runs once per unit the condition counts down over.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.