Boolean Values
Every comparison has an answer: yes or no. In C++, these answers are the values true and false. They're called boolean values, after the mathematician George Boole, and you already know their data type from the lesson on variables: bool. So you can store the result of a comparison in a variable, print it and use it as a condition:
int age = 20;
bool isAdult = age >= 18;
std::cout << "Adult: " << isAdult << std::endl;
if (isAdult) {
std::cout << "You can vote" << std::endl;
}This prints:
Adult: 1
You can voteRead the second line of code from the right: the program first compares age >= 18, which gives true, and then = stores that value in isAdult. As you already know, std::cout prints true as 1 and false as 0. The condition if (isAdult) means the same as if (isAdult == true). It's just shorter, which is why programmers write it that way.
Names of boolean variables usually start with is or has (isAdult, hasTicket), so that they read like a yes-or-no question.
A boolean variable comes in handy for even numbers, for example. A number is even when nothing is left over after dividing it by two, that is, when the remainder number % 2 is 0:
int number = 14;
bool isEven = number % 2 == 0;
std::cout << "Even: " << isEven << std::endl;This prints:
Even: 1The program first calculates the remainder 14 % 2, which is 0, and only then compares it with zero: % goes before ==, just as multiplication goes before addition. For an odd number, say 7, the remainder is 1 and isEven is false. If you wrote a single equals sign here by mistake, number % 2 = 0, the compiler would report error: expression is not assignable, because you can't store anything in the result of a calculation. Here the compiler catches the mix-up of = and ==, unlike if (points = 10) in the previous exercise.
Instructions
- 1
Create a
boolvariableisEvenholding the result of the comparisonnumber % 2 == 0, and print it:std::cout << "Even: " << isEven << std::endl;. The number 7 isn't even, so the program printsEven: 0. - 2
Below that line, write an
ifstatement with the conditionisEventhat printsThe number is even, and give it anelsebranch that printsThe number is odd. The program prints:Number: 7 Even: 0 The number is odd