4.14. Logical operatorsΒΆ
There are three logical operators in C++:
AND, OR, and NOT, which are normally denoted by the symbols
&&, || and !.
The semantics (meaning) of these operators is similar to their meaning in English.
For example x > 0 && x < 10 is true only if x
is greater than zero AND less than 10.
even || n%3 == 0 is true if either of the conditions is true,
that is, if the bool variable even is true OR the number is divisible by 3.
Finally, the NOT operator has the effect of negating or inverting a bool
expression, so !even is true if even is false; that is, if the
number is odd.
Logical operators often provide a way to simplify nested conditional statements.
Q1
Multiple Response: How could you re-write the following code using a single conditional?
if (x > 0) {
if (x < 10) {
cout << "x is a positive single digit" << '\n';
}
}
Q2
Match the conditional statement to the correct boolean and the meaning of the operator in use, given n = 7.
Q3
- Add a single logical operator to make the expression check if x is greater than or equal to 50
( x < 50 )
More to Explore
logical operators from cppreference