3.1 Boolean Operators

There are times in programs where you will need to make more complex decisions. You may need to make a choice based on the value of more than one variable. There are three boolean operators that you can use to make more complex boolean expressions. The three operators are and, or, and not.

Suppose you had the following declaration:

var p, q : boolean 

These boolean operators can be summarized in the following truth table:

p
q
p and q
p or q
not p
true
true
true
true
false
true
false
false
true
false
false
true
false
true
true
false
false
false
false
true

Each of these operators has a different precedence in the order of operations. The operator with the highest precedence of the three is not. The next highest is and. The lowest is or. Here is a table that outlines the order of operations for all the operators we've seen so far. Operators on the same line have the same precedence.

**
* / div mod
+ - 
< <= = not= > >=
not
and
or

Here are some examples using boolean operators:

Take note of the last example. Remember that ands are executed before ors. If you do the or first you will get the wrong answer. Here is a small program using two of the new operators:
var age : int
put "Please enter your age"
get age
% negative ages or ages that are too old are not possible
if age < 0 or age > 120 then
   put "Do you really expect me to believe you are that age"
end if
% ages 13, 14, 15,16, 17, 18, 19 are teen ages
if age >= 13 and age <= 19 then
   put "You are a teenager"
end if 

Exercise 3.1

  1. Evaluate the expressions that are legal. If an expression is not legal, state the reason for its being illegal.
    1. true and not false
    2. false or not true
    3. not (true or not false)
    1. not (4 not= 2 + 2)
    2. not 5 < 7
    3. not (5 <= 8) or not false
  2. Variables p, q, r, s are declared as:
    var p, s : boolean := true
    var q, r : boolean := false

    State the value of each expression.
    1. not p
    2. p or q
    3. p and r
    4. not (q and s)
    5. not q and s
    1. s and not q
    2. p or not s
    3. not p and not q
    4. s or (not q and r)
    5. p = (q or r)
  3. Boolean expressions can often be simplified using a pair of rules known as de Morgan's laws. These laws state that:
    M1: not (p and q) is equivalent to (not p) or (not q)
    M2: not (p or q) is equivalent to (not p) and (not q)

    Use de Morgan's laws and the fact that not(not p) is equivalent to p to simplify each expression.

    1. not (p and not q)
    2. not (not p and not q)
    3. not (not p or not q)
    4. not ((x not= 0) and not (y = 0))
  4. The exclusive or operator, xor, has the following truth table.

    p
    q
    p xor q
    true
    true
    false
    true
    false
    true
    false
    true
    true
    false
    false
    false

    Using only and, or, not write an expression that is true if and only if p xor q is true.