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.
Lesson 7 of 45
C++10 min
Keep these ideas in mind as you work through the lesson.
for, while, do‑whileLoops 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.
// 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
breakto exit early andcontinueto skip the remainder of the current iteration.