C++ Tutorial: Loops
for, while, do-while, range-based for, break, continue — all of C++'s looping constructs.
Repetition is computation
Loops are the engine of every algorithm. C++ loops are identical to Java and C — but C++11 added the elegant range-based for loop that eliminates index management entirely.
What you'll learn in this C++ loops tutorial
This interactive C++ tutorial has 7 hands-on exercises. Estimated time: 16 minutes.
- for loop — Classic for loop: init, condition, update:
- Range-based for — iterate containers — C++11 range-based for is cleaner when you don't need the index:
- while loop — `while` loops while the condition is true. Use when you don't know the iteration count upfront.
- do-while — run at least once — `do-while` executes the body first, then checks the condition — guaranteed one run.
- break and continue — - `break` — exit the loop immediately
- Nested loops — Loops inside loops. The inner loop runs completely for every outer iteration.
- FizzBuzz — The classic programming interview test — print 1 to 30:
C++ Loops concepts covered
- Repetition is computation