Logic and Math
Chapter 4
Everything is a Number
Remember, to a computer, everything is a number, even characters.
Truth Tables
A convenient and helpful way to organize the possible values of any logical (Boolean) statement is in a truth table. A truth table is a table whose column headings are expressions, and whose rows are possible scenarios given the expressions. For example, in the NOT table below, if p is true
(T), then “not p” (!p) must be false
(e.g., if p means it “is raining” then !p means it is “not raining”).
p | !p |
---|---|
T | F |
F | T |
p | q | p && q |
---|---|---|
T | T | T |
T | F | F |
F | T | F |
F | F | F |
p | q | p || q |
---|---|---|
T | T | T |
T | F | T |
F | T | T |
F | F | F |
Examples
p | q | p || q | ! (p || q) |
---|---|---|---|
T | T | T | F |
T | F | T | F |
F | T | T | F |
F | F | F | T |
p | q | !p | !q | !p && !q |
---|---|---|---|---|
T | T | F | F | F |
T | F | F | T | F |
F | T | T | F | F |
F | F | T | T | T |
Note that !(p || q) has the same truth-table results as !p && !q. That means that the two statements are logically equivalent.
Operator Precedence
- Relational and logical operators are evaluated from left to right
- The associativity is left to right
- Parentheses can override precedence
Operators | Precedence |
---|---|
! , + , - (unary operators) | first |
* , / , % | second |
+ , - | third |
< , <= , >= , > | fourth |
== , != | fifth |
&& | sixth |
|| | seventh |
= | last |
Try to create more advanced combinations for truth tables like:
q || !q && p != q
What does this evaluate to?
1 + 7 < 2 || !5 + -1 && true == 0
Remember false
is 0
and true
is a nonzero value.
Short-Circuit Evaluation
Short-circuit evaluation is the evaluation of a logical expression that stops as soon as the value of the expression is known.
Example:
cpp(age >= 21) || ( x == 5) //Line 1 (grade == 'A') && (x >= 7) //Line 2
Example to prevent dividing by zero.
cppint demon = 1, num = 4; if(denom != 0 && num / denom > 0) cout << num << " has the same sign as " << denom << endl;
Trick, trick question: If the value of num
is 0
, what is it after: if(num && num = 2) …
?
Answer: num
would still equal 0
. But it would equal 2
if you changed the &&
to ||
.
Self-Check Questions
- Be able to fill in the truth tables.
- Use truth tables to determine if two expressions are logically equivalent.
- Does the following expression evaluate to
true
orfalse
?1 + 2 < 10 || (4 * 2 != 9 && -4 / 2 <= -4)