Show contents
Chapter 1 of 6 · 20 min
if, else and switch
By the end of this chapter, you'll be able to
- Write a condition with if, else if and else
- Combine conditions with &&, || and !
- Use switch to choose between exact values
- Avoid mixing up = and ==
if, else if, else
#include <iostream>
int main() {
double amount = 42.0;
bool subscriber = false;
if (amount >= 50) {
std::cout << "Free delivery\n";
} else if (subscriber) {
std::cout << "Delivery: 1.99\n";
} else {
std::cout << "Delivery: 4.99\n";
}
return 0;
}
Delivery: 4.99
- The condition is written between parentheses, the block between curly braces.
- The conditions are tested from top to bottom, and only the first block whose condition is true runs. The final
elsecatches every other case. - A condition is a value of type
bool. Comparisons produce one:==(equal),!=(not equal),<,<=,>,>=.
Combining conditions
&&(and): true if both sides are true;||(or): true if at least one side is true;!(not): inverts the condition.
The if condition is true: the message is displayed.
Text description of the animation
- A shop is open from 9 am to 6 pm, except on public holidays.
- It's 2 pm.
- It isn't a public holiday.
- We evaluate from left to right. First part: true.
- Second part: true as well.
- !holiday turns false into true. All three parts are true: open is true.
- The if condition is true: the message is displayed.
C++ stops as soon as the result is known: in a && b, if a is false, b isn't even evaluated. This is called short-circuiting. It lets you write divisor != 0 && total / divisor > 10 without risking a division by zero.
switch: choosing between exact values
#include <iostream>
int main() {
int day = 6;
switch (day) {
case 6:
case 7:
std::cout << "Weekend\n";
break;
case 3:
std::cout << "Wednesday: afternoon off\n";
break;
default:
std::cout << "School day\n";
break;
}
return 0;
}
Weekend
switch compares an integer (or a char) with fixed values. Each case ends with break, which leaves the switch. Two cases stuck together, like case 6: and case 7: here, share the same code. default handles all the other values. Careful: switch doesn't work with a std::string. To compare texts, use ifs with ==.
Your turn
Worked exercise
Worked exercise: the body mass index
BMI is calculated with the formula weight / (height × height), with the weight in kilos and the height in metres. Display the matching category: under 18.5, "Underweight"; from 18.5 to under 25, "Normal weight"; from 25 to under 30, "Overweight"; 30 or more, "Obesity". For 70 kg and 1.75 m, the program must display BMI 22.9: Normal weight.
Hint 1
bmi < 18.5, else if bmi < 25, and so on. Each else if already knows that the previous conditions were false.Hint 2
std::fixed << std::setprecision(1) from <iomanip>.Show the solution and common mistakes
#include <iostream>
#include <iomanip>
#include <string>
int main() {
double weight = 70.0;
double height = 1.75;
double bmi = weight / (height * height);
std::string category;
if (bmi < 18.5) {
category = "Underweight";
} else if (bmi < 25) {
category = "Normal weight";
} else if (bmi < 30) {
category = "Overweight";
} else {
category = "Obesity";
}
std::cout << std::fixed << std::setprecision(1) << "BMI " << bmi << ": " << category << "\n";
return 0;
}
BMI 22.9: Normal weight
Common mistakes:
- Writing
weight / height * height: without parentheses, the calculation runs from left to right and simply gives the weight. - Testing
bmi >= 18.5 && bmi < 25in every branch: it isn't wrong, but it's unnecessary after anelse if, and it multiplies the risk of mistakes at the boundaries.
Summary
- 1if (…) { … } else if (…) { … } else { … }: only the first true block runs.
- 2Comparisons (==, !=, <, <=, >, >=) produce a bool.
- 3&&, || and ! combine conditions, with short-circuiting from left to right.
- 4switch compares an integer with fixed cases; end each case with break.
- 5= stores, == compares: -Wall catches the mix-up.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.