Lesson 3
Making decisions
Short answer: if (condition) runs the next block only when the condition is true; else runs the alternative. A condition is just an expression that evaluates to true or false.
Comparisons produce bools
| Operator | Means | Example |
|---|---|---|
== | equal | a == 5 |
!= | not equal | a != 5 |
< > <= >= | ordering | a <= 10 |
You can print a comparison to see its 1/0 value — a quick way to check what C++ actually thinks:
#include <iostream>
using namespace std;
int main() {
int x = 7;
cout << (x > 5) << endl; // 1 (true)
cout << (x == 5) << endl; // 0 (false)
cout << (x != 5) << endl; // 1
return 0;
}
Three-way choice
else if chains tests in order and stops at the first true one:
#include <iostream>
using namespace std;
int main() {
int score;
cin >> score;
if (score >= 90) cout << "A" << endl;
else if (score >= 80) cout << "B" << endl;
else if (score >= 70) cout << "C" << endl;
else cout << "F" << endl;
return 0;
}
Try 95, 85, 75, 60 in the input box. Order matters: once score >= 90 is true, the later tests never run.
Combining conditions
&& means and (both must be true), || means or (at least one), ! means not. The leap-year rule is the classic three-way combination:
#include <iostream>
using namespace std;
int main() {
int year;
cin >> year;
bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (leap) cout << "leap year" << endl;
else cout << "not a leap year" << endl;
return 0;
}
Try 1900 (not leap), 2000 (leap), 2024 (leap). The full story of why the century rule exists is in this article's cousin — or just solve the problem.
The traps
=vs==.if (x = 5)assigns 5 and is always true — a silent bug. Readif (5 == x)if you want the compiler to catch it.- Missing braces.
if (a) if (b) x(); else y();— theelsebinds to the nearestif. Always use braces. - Chained comparisons.
0 < x < 10compiles and is wrong (it means(0 < x) < 10). Write0 < x && x < 10.