Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 43 of 45 · C++

Lesson 7: Loops – for, while, do‑while

Duration: 10 min

Loops – 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

Note

Infinite loops are created by writing a condition that never becomes false. Always ensure a loop modifies its condition.

Previous: Lesson 6: Control Flow – if, else, switchNext: Lesson 8: Functions