Lesson 43 of 45 · C++
Lesson 7: Loops – for, while, do‑while
Duration: 10 min
Lesson 43 of 45 · C++
Duration: 10 min
for, while, do‑while\n\nLoops allow repetitive execution of a block of code. C++ provides three classic loop constructs:\n- for – ideal when the iteration count is known.\n- while – checks the condition before each iteration.\n- do‑while – executes the body at least once, then checks.\n\nSince C++11, the range‑based for loop provides a concise syntax for iterating over containers.\n\n---\n\n## Example: Classic and Range‑Based Loops\ncpp\n// Classic for loop\nfor (int i = 0; i < 5; ++i) {\n std::cout << i << ' ';\n}\nstd::cout << '\\n';\n\n// While loop\nint n = 5;\nwhile (n > 0) {\n std::cout << n << ' ';\n --n;\n}\nstd::cout << '\\n';\n\n// Do‑while loop – prints at least once\nint x = 0;\ndo {\n std::cout << \"Executed \" << x << \" times\\n\";\n ++x;\n} while (x < 3);\n\n// Range‑based for over a std::vector\nstd::vector<int> vec = {10, 20, 30};\nfor (int v : vec) {\n std::cout << v << '\\n';\n}\n\n\n> Tip: Use break to exit early and continue to skip the remainder of the current iteration.\n\n---\n\n