Loops
2 min read
Loops
Loops repeat a block of code. C++ has four loop forms: for, range-based for, while, and do-while.
for loop
The classic for loop has three parts: initialization, condition, and increment:
#include <iostream>
int main() {
for (int i = 0; i < 5; i++) {
std::cout << i << " ";
}
std::cout << "\n"; // 0 1 2 3 4
}
Any part can be omitted. for (;;) is an infinite loop equivalent to while (true).
Counting down
for (int i = 10; i > 0; i--) {
std::cout << i << " ";
}
std::cout << "go!\n";
Range-based for
Iterates over every element of a container or array without dealing with indices:
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {10, 20, 30, 40, 50};
for (int n : nums) {
std::cout << n << " ";
}
std::cout << "\n";
}
Use const auto& to avoid copying large elements:
std::vector<std::string> words = {"alpha", "beta", "gamma"};
for (const auto& w : words) {
std::cout << w << "\n";
}
Use auto& (without const) when you need to modify the elements in place:
for (auto& n : nums) n *= 2;
while loop
Checks the condition before each iteration:
#include <iostream>
int main() {
int n = 1;
while (n <= 5) {
std::cout << n << " ";
n++;
}
std::cout << "\n"; // 1 2 3 4 5
}
do-while loop
Checks the condition after each iteration — the body always runs at least once:
#include <iostream>
int main() {
int input;
do {
std::cout << "Enter a positive number: ";
std::cin >> input;
} while (input <= 0);
std::cout << "Got: " << input << "\n";
}
break and continue
break exits the innermost loop immediately. continue skips the rest of the current iteration and jumps to the next:
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 7) break; // stop at 7
if (i % 2 == 0) continue; // skip even numbers
std::cout << i << " ";
}
std::cout << "\n"; // 1 3 5
}
Nested loops and labels
C++ has no loop labels, but you can use a flag variable or a goto to break out of nested loops:
bool found = false;
for (int i = 0; i < 5 && !found; i++) {
for (int j = 0; j < 5; j++) {
if (i * j == 6) { found = true; break; }
}
}
Or restructure the inner loop into a function and use return.
Loop variable lifetime
Variables declared inside a for initializer are scoped to the loop:
for (int i = 0; i < 3; i++) { /* i exists here */ }
// i does not exist here
Learn modern C++ through working code. Each chapter introduces one concept — variables, functions, classes, templates, smart pointers, concurrency — with a clear example, a line-by-line explanation, and notes on how it applies in real programs.
View book →