while Loop in C++
while repeats a block for as long as its condition holds, testing before each pass — including the first, so the body may run zero times. It fits open-ended repetition where the endpoint isn't known up front: reading until EOF, waiting for valid input, converging a computation.
Because the update lives inside the body (not in a header), forgetting it builds an infinite loop — the most common while bug. Structure input loops as while (cin >> x) so a failed read ends the loop by itself.
Test-first repetition
while (n > 0) checks before every iteration — if n starts at 0, the body never runs, unlike do-while.
Update inside the body
Something in the body must move toward termination (n--, reading input, advancing a pointer) or the loop never ends.
Stream conditions
while (std::cin >> x) loops over all input and stops cleanly at EOF or bad data — the idiomatic C++ input loop.
Sentinel patterns
Read-then-test loops (ask, check for quit-word, process) map naturally onto while with the read duplicated before and inside.
#include <iostream> int main() { int n = 5; int fact = 1; while (n > 1) { fact *= n; --n; } std::cout << fact << std::endl; 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.