Loops in C++

From the C++ cheat sheet · Control Flow · verified Jul 2026

Loops

for, range-for, while, and do-while.

cpp
// Quick Reference
for (int i = 0; i < 5; i++) { ... }
for (auto x : container) { ... }   // range-for
while (cond) { ... }
do { ... } while (cond);
💡 Use range-for (for (auto x : c)) when you do not need the index.
⚡ Iterate large elements by const auto& to avoid copying each one.
📌 Use auto& (non-const) in range-for when you need to modify elements in place.
🟢 do-while always runs the body once before testing - handy for input retry loops.
loopsrange-for

More C++ tasks

Back to the full C++ cheat sheet