Module 7: Control StatementsBeginner40 min read
Loops in C++: for, while, do-while, Range-Based for & Jump Statements
Master iteration with for, while, do-while, C++11 range-based for loops, nested loops, break, continue, and avoiding infinite loop bugs.
Key Takeaways & Core Concepts
- `for`: Known iteration count (
for (int i = 0; i < n; ++i)). - `while`: Entry-controlled; runs 0 or more times.
- `do-while`: Exit-controlled; guaranteed at least 1 execution (ideal for menus).
- Range-based `for` (C++11):
for (const auto& x : container)— eliminates off-by-one bugs!
1. Loop Constructs Compared
- `for`: Known iteration count (
for (int i = 0; i < n; ++i)). - `while`: Entry-controlled; runs 0 or more times.
- `do-while`: Exit-controlled; guaranteed at least 1 execution (ideal for menus).
- Range-based `for` (C++11):
for (const auto& x : container)— eliminates off-by-one bugs!
1. Range-Based For with Mutation & Filtering
1#include <iostream>
2#include <vector>
3
4int main() {
5 std::vector<int> v = {1, 2, 3, 4, 5};
6 for (int& x : v) x *= 2;
7 for (const int x : v) {
8 if (x == 6) continue;
9 std::cout << x << " ";
10 }
11 return 0;
12}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines
Note: `int& x` doubles elements in-place; `continue` skips 6.
2. Loop Control & Common Mistakes
breakexits the innermost loop;continuejumps to the next iteration.- Mistake: Using
for (auto x : vec)on large strings/objects copies every element! Useconst auto&for reading andauto&for mutating.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)