Learn C++
#include "controlflow/while_loop.hpp"

while Loop in C++

//concept

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.

//how it works
1

Test-first repetition

while (n > 0) checks before every iteration — if n starts at 0, the body never runs, unlike do-while.

2

Update inside the body

Something in the body must move toward termination (n--, reading input, advancing a pointer) or the loop never ends.

3

Stream conditions

while (std::cin >> x) loops over all input and stops cleanly at EOF or bad data — the idiomatic C++ input loop.

4

Sentinel patterns

Read-then-test loops (ask, check for quit-word, process) map naturally onto while with the read duplicated before and inside.

//example
#include <iostream>
 
int main() {
int n = 5;
int fact = 1;
while (n > 1) {
fact *= n;
--n;
}
std::cout << fact << std::endl;
return 0;
}
Output
120
1n starts at 5; each pass multiplies fact by n, then decrements n toward the exit condition.
2The passes compute 1*5*4*3*2 = 120, stopping once n reaches 1.
3Without --n the condition would stay true forever — the update is what guarantees termination.
//complexity
time O(n)
space O(1)

Runs once per unit the condition counts down over.

//use cases
Reading all of stdin with while (cin >> x) until EOF
Input-validation loops that repeat until data parses
Countdown and convergence loops with data-dependent exits
Polling loops that break on an external condition

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.