Learn C
#include "controlflow/while_loop.h"

while Loop in C

#concept

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.

#how it works
1

Test-first repetition

while (n > 0) checks before every iteration — starting at 0 means zero passes, unlike do-while.

2

Update inside the body

Something must move toward termination, or the loop never ends — the update is the whole termination argument.

3

Stream conditions

while ((c = getchar()) != EOF) loops over all input and stops cleanly — the idiomatic C input loop.

4

Zero-trip awareness

Empty input, already-satisfied goals, and failed first reads all skip the body — initialize results for that case.

#example
#include <stdio.h>
 
int main(void) {
int n = 5;
int fact = 1;
while (n > 1) {
fact *= n;
--n;
}
printf("%d\n", fact);
return 0;
}
Output
120
1n starts at 5; each pass multiplies fact by n, then decrements toward the exit.
2The passes compute 1*5*4*3*2 = 120, stopping at n == 1.
3Without --n the condition would hold forever — the update guarantees termination.
#complexity
time O(n)
space O(1)

Runs once per unit the condition counts down over.

#use cases
Reading all of stdin until EOF
Input-validation loops repeating until data parses
Draining buffers and queues of unknown length
Polling loops breaking on external conditions

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.