Conditions: if / else / switch
Teach your program to make decisions
- use
ifto run code only when something is true, - use
if / elseto pick between two paths, - chain
else ifto test several conditions in order, - use
switchto choose cleanly among many fixed values.
1. The idea: a fork in the road
Imagine walking and reaching a fork in the road. You ask a yes/no question — "Is it raining?" — and pick a path based on the answer. Your program does the same. It checks a condition (a question that is either true or false) and runs different code for each answer.
In C++ we ask these questions with comparison operators. Each one gives back true or false:
| Operator | Means | Example (true when) |
|---|---|---|
== | is equal to | x == 5 (x is 5) |
!= | is not equal to | x != 5 (x is not 5) |
> | greater than | x > 5 |
< | less than | x < 5 |
>= | greater than or equal | x >= 5 |
<= | less than or equal | x <= 5 |
Careful: == asks "are these equal?" while a single = assigns a value. They are not the same!
2. The if statement
An if runs a block of code only when its condition is true. If the condition is false, the block is skipped.
#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age >= 18) {
cout << "You are an adult." << endl;
}
return 0;
}
Output: You are an adult.
Because age is 20 and 20 >= 18 is true, the message prints. If age were 12, the condition would be false and nothing would print. The { } braces hold everything the if controls.