C++: Control Flow
What you will learn
How to write conditionals and loops in C++, and the difference between for, while, and do-while loops.
if / else if / else
int score = 85;
if (score >= 90) {
std::cout << "A";
} else if (score >= 80) {
std::cout << "B";
} else {
std::cout << "F";
}
Note else if is two words (not elif). Curly braces are required for multi-statement blocks.
Loops
for loop
for (int i = 0; i < 5; i++) {
std::cout << i << " "; // 0 1 2 3 4
}
while loop
int i = 0;
while (i < 5) {
std::cout << i++ << " ";
}
do-while loop (always runs at least once)
int i = 0;
do {
std::cout << i++ << " ";
} while (i < 5);
Range-based for (C++11+)
int numbers[] = {1, 2, 3, 4, 5};
for (int n : numbers) {
std::cout << n << " ";
}
Common mistakes
- Writing
if (x = 5)instead ofif (x == 5)— the first assigns 5 to x and always evaluates totrue. Compile with warnings (-Wall) to catch this. - Forgetting the semicolon at the end of
do { ... } while (condition); - Using
=inside a loop condition when you meant== - Forgetting that arrays and other container indexes are zero-based
Quick check below!