DevAcademia lesson/C++ Basics
While Loop
Topic progressTopic 44 of 109 - 40% complete
~7 min lesson24 learning blocks6 code examples1 checks/interactions
Lesson outline
Introduction to While Loops
The while loop executes a block of code repeatedly as long as the specified condition evaluates to true.
It is especially useful when the number of iterations is not known beforehand and depends on runtime conditions.
Basic Syntax
Simple Example
Infinite Loops
A while loop will become infinite if its condition never becomes false. This can be intentional for servers or background tasks, but must be carefully controlled:
Loop Control
Special statements can alter the flow of a while loop:
| Statement | Effect |
|---|---|
| break | Exits the loop immediately |
| continue | Skips the rest of the current iteration and continues with the next |
| return | Exits the entire function, ending the loop as well |
While vs Do-While
A do-while loop checks its condition after executing the body, so it runs at least once:
Common Patterns & Pitfalls
- Off-by-one errors: double-check boundary conditions (e.g.,
<=vs<). - Make sure the loop body eventually changes the condition; otherwise you'll loop forever.
- Avoid using floating-point equality in loop conditions due to rounding (prefer counters or tolerances).
Was this topic clear?