ReviseAlgo Logo

Control Flow

While and Do-While Loops

Condition-based iteration with while and do-while constructs

Interview: Essential loop pattern — common in input validation, event loops, and sentinel-controlled iteration

While and Do-While Loops

While loops repeat a block of code as long as a condition remains true. Unlike the for loop (which is ideal for counted iteration), the while loop is the natural choice for sentinel-controlled and event-driven loops where the number of iterations is not known in advance.

The while Loop

The condition is checked before each iteration. If the condition is false on the first check, the body never executes. This is called a pre-test loop. The condition must eventually become false, otherwise the loop runs forever.

The do-while Loop

The body executes first, then the condition is checked. This guarantees the body runs at least once regardless of the condition — called a post-test loop. The canonical use case is input validation: prompt the user, then check if the input is valid.

Infinite Loops and Event Loops

while (true) creates an intentionally infinite loop, exited via break or return. This pattern is foundational for game loops, server event loops, and interactive command-line programs.

Reading Until EOF

while (cin >> x) reads until end-of-file or a parse failure. The cin >> x expression returns a reference to the stream, which converts to bool: true if the read succeeded, false on EOF or error. This idiomatic pattern avoids a separate boolean flag entirely.

Loop Condition Check Min Executions Best For
whileBefore body0Sentinel-controlled, unknown iterations
do-whileAfter body1Input validation, must-run-once
forBefore body0Counted iteration, known range

Interview Corner

Q: When would you choose do-while over while?

A: When you need the body to execute at least once before checking the condition. The clearest case is input validation loops: you must read input before you can check whether it is valid. With a regular while loop, you'd need to duplicate the read before the loop and again inside it (or use an artificial flag). do-while avoids that duplication cleanly.

Q: How does while (cin >> x) work?

A: The expression cin >> x returns a reference to std::istream. std::istream has an operator bool() that returns true if no error bits are set. On successful read it returns true; on EOF or parse failure (e.g., reading "abc" into an int) it returns false. This idiom naturally terminates at EOF — key for processing piped or file input.

Q: What is the difference between a while loop and recursion?

A: Both express repeated operations. Loops use stack space only for local variables; recursion pushes a new stack frame per call (O(n) stack for n recursive calls). Tail-call optimization can eliminate stack growth for tail-recursive functions, but C++ does not mandate TCO. For deep recursion, iterative solutions with explicit stacks are safer. Loops are generally preferred for performance-critical code.

Common Pitfalls

  • Infinite loop due to missing update: Forgetting to update the loop variable inside the body — the condition never becomes false.
  • Off-by-one with do-while: If the initial value is already invalid, do-while still executes once. Ensure the first iteration either produces a valid state or handles the initial invalid state gracefully.
  • Using = instead of == in condition: while (x = getValue()) assigns, not compares. This is sometimes intentional but easily confused. If intentional, use while ((x = getValue()) != 0) for clarity.
  • Forgetting semicolon after do-while: The do-while loop ends with } while (condition); — the semicolon is mandatory. Missing it is a compile error.

Best Practices

  • Prefer the for loop for counted iteration; use while for condition-driven loops where the count is not known upfront.
  • Limit the body of while (true) loops to a single clear exit point using break. Multiple break points in different branches make control flow hard to follow.
  • After a while (cin >> x) loop, check cin.fail() vs cin.eof() to distinguish between parse errors and normal termination.