C++ Tutorial · Control Flow and Functions · Lesson 8 of 21
C++ Conditions and Loops
if, switch, for, range-based for, while and do-while.
Conditions
#include <iostream>
int main() {
int temp = 31;
if (temp > 30) {
std::cout << "Hot\n";
} else if (temp > 20) {
std::cout << "Warm\n";
} else {
std::cout << "Cold\n";
}
char grade = 'B';
switch (grade) {
case 'A': std::cout << "Excellent\n"; break;
case 'B':
case 'C': std::cout << "Good\n"; break;
default: std::cout << "Keep going\n";
}
if (int n = temp / 10; n == 3) std::cout << "if with initializer: " << n << '\n';
}
Output
Hot Good if with initializer: 3
Run this on your computer — see “Get Started” for setup.
Loops
The range-based for loop is the modern way to visit every element. Use const auto& to avoid copying:
#include <iostream>
#include <string>
#include <vector>
int main() {
for (int i = 0; i < 3; ++i) std::cout << i << ' ';
std::cout << '\n';
std::vector<std::string> langs{"C++", "Rust", "Zig"};
for (const auto& lang : langs) std::cout << lang << ' ';
std::cout << '\n';
int n = 1;
while (n < 100) n *= 3;
std::cout << n << '\n';
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0) continue;
if (i > 7) break;
std::cout << i << ' ';
}
std::cout << '\n';
}
Output
0 1 2 C++ Rust Zig 243 1 3 5 7
Run this on your computer — see “Get Started” for setup.
Test yourself
Why write for (const auto& x : items)?
To modify each elementTo read each element without copying itTo loop backwardsIt's required syntax
Show answer
Answer: To read each element without copying it