Quiz
Warm-up from lesson 2-1: what does `std::cout << (5 > 3);` print by default?
Control flow is where a program stops being a calculator and starts making decisions. Input validation, game logic, and the edge-case handling that separates an accepted DSA solution from a rejected one are all ifs and loops arranged carefully. C++'s versions look almost identical to Python's, so this unit is mostly about the few traps where they differ.
if / else if / else
Same idea as Python, different clothing: the condition goes in parentheses, the body goes in braces, and there is no elif, just else if.
int score = 87; if (score >= 90) { std::cout << "A\n"; } else if (score >= 80) { std::cout << "B\n"; } else { std::cout << "C or below\n"; }
Comparisons: == != < <= > >=. Logic: && is Python's and, || is or, ! is not.
Two classic traps:
=assigns,==compares.if (x = 5)assigns 5 to x and is always true. Most compilers warn, always read the warning.- Braces are optional for a single statement, but skipping them causes real bugs when a second line is added later. Always write the braces.
Code exercise · cpp
Run this. It reads a temperature and classifies it with an if / else if / else chain. Input is 31.
Quiz
What is the bug in `if (lives = 0) { std::cout << "game over"; }`?
Code exercise · cpp
Your turn. Read one int and print `even` or `odd`. Recall the % operator from lesson 2-2: n % 2 is 0 exactly when n is even. Input is 42.