If-Else Statement
An if alone decides whether to do one thing. Add else, and you can choose between two things. When the condition is true, the first body runs. When it is false, the else body runs.
#include <iostream>
using namespace std;
int main() {
int price = 80;
int budget = 50;
if (price <= budget) {
cout << "You can afford it" << "\n";
} else {
cout << "Too expensive" << "\n";
}
return 0;
}
Output:
Too expensive
80 is not less than or equal to 50, so price <= budget is false and the else body runs. Change the price to 40 and the other body runs instead:
int price = 40;
int budget = 50;
if (price <= budget) {
cout << "You can afford it" << "\n";
} else {
cout << "Too expensive" << "\n";
}
Output:
You can afford it
Exactly one of the two bodies runs every time. Never both, and never neither.
Notice that else has no condition of its own. It means "in every other case". You do not need to write price > budget there, because the else already covers it.
Using the remainder in a condition
The % operator from the Operators lesson gives the remainder of a division. It is very useful in conditions. For example, a number of minutes is a whole number of hours when dividing it by 60 leaves no remainder:
int minutes = 135;
if (minutes % 60 == 0) {
cout << "Whole hours" << "\n";
} else {
cout << minutes % 60 << " extra minutes" << "\n";
}
Output:
15 extra minutes
135 divided by 60 is 2, with 15 left over. The remainder is not 0, so the else body runs and prints it.
In the exercise, read a number and print Even or Odd.