Branch and loop: if/else and switch, for/while/do-while, and the range-based for loop that iterates any container cleanly.
Branches choose a path. switch dispatches on an integer or enum value; each case falls through to the next unless you break, so break is almost always what you want. C++17 lets you declare a variable inside the if condition.
#include <iostream>
int classify(int score) {
if (score >= 90) return 1; // A
else if (score >= 70) return 2; // B
else return 3; // C
}
int main() {
int day = 3;
switch (day) {
case 1: std::cout << "Mon\n"; break;
case 3: std::cout << "Wed\n"; break;
default: std::cout << "other\n"; break;
}
if (int r = classify(85); r == 2) // C++17 init-statement
std::cout << "grade B\n";
return 0;
}The classic for loop bundles init, condition, and step. while tests before the body; do-while runs the body at least once, then tests. continue skips to the next iteration; break exits the loop entirely.
#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
if (i == 2) continue; // skip 2
std::cout << i << ' '; // 0 1 3 4
}
std::cout << "\n";
int n = 3;
while (n > 0) { std::cout << n-- << ' '; } // 3 2 1
std::cout << "\n";
int tries = 0;
do {
++tries; // runs at least once
} while (tries < 3);
return 0;
}The cleanest way to visit every element of a container or array. Use const auto& to read without copying, and auto& when you need to modify elements in place. Prefer this over manual index loops — it cannot run off the end.
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums{10, 20, 30};
for (const auto& x : nums) // read-only, no copies
std::cout << x << ' '; // 10 20 30
std::cout << "\n";
for (auto& x : nums) x *= 2; // modify in place -> 20 40 60
for (int x : nums) std::cout << x << ' ';
return 0;
}