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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 7: Loops – for, while, do‑while | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 7 of 45

·C++

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

10 min

Course progress16%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Traditional for loop syntax
  • Range‑based for loop
  • While and do‑while differences
  • Loop control (break, continue)

Loops – for, while, do‑while

Loops allow repetitive execution of a block of code. C++ provides three classic loop constructs:

  • for – ideal when the iteration count is known.
  • while – checks the condition before each iteration.
  • do‑while – executes the body at least once, then checks.

Since C++11, the range‑based for loop provides a concise syntax for iterating over containers.


Example: Classic and Range‑Based Loops

// Classic for loop
for (int i = 0; i < 5; ++i) {
    std::cout << i << ' ';
}
std::cout << '\
';

// While loop
int n = 5;
while (n > 0) {
    std::cout << n << ' ';
    --n;
}
std::cout << '\
';

// Do‑while loop – prints at least once
int x = 0;
do {
    std::cout << \"Executed \" << x << \" times\
\";
    ++x;
} while (x < 3);

// Range‑based for over a std::vector
std::vector<int> vec = {10, 20, 30};
for (int v : vec) {
    std::cout << v << '\
';
}

Tip: Use break to exit early and continue to skip the remainder of the current iteration.


Note

Infinite loops are created by writing a condition that never becomes false. Always ensure a loop modifies its condition.
Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 6: Control Flow – if, else, switchContinue to lesson 8Lesson 8: FunctionsBack to C++ Course curriculum