# Advanced Boolean algebra in programming

When we want to doo a simple test on some data, we use a maths operator. We can combine tests by using Boolean operators. We need to know our truth tables to be able to combine tests. Remember, 1 in a truth table stands for TRUE and 0 stands for FALSE.

**Example 1**

Conside this problem:

** (34 >= 34) AND (23 < 5) **

This is like an AND gate, with (34 >= 34) as one input and (23 < 5) as the other input.

When we refer to the truth table for an AND gate, we can see that both inputs must be TRUE for the output to be TRUE.

** So, (34 >= 34) is TRUE.**** But (23 < 5) is FALSE.**

Looking at the truth table, if the first input is 1 (TRUE) and the second is 0 (FALSE), then the output is 0 (FALSE).

**Example 2**

Consider this problem:

** (16 < 4) OR (121 > 45)**

This is like an OR gate, with (16 < 4) as one input and (121 > 45) as the other input.

When we refer to the truth table for an OR gate, we can see that at least one input must be TRUE for the output to be TRUE. ** So, (16 < 4) is FALSE**** but (121 > 45) is TRUE**

Looking at the truth table, if the first input is 0 (FALSE) and the second is 1 (TRUE), then the output is 1 (TRUE).

**Example 3**

Consider this problem:

** NOT((16 < 4) OR (121 > 45))**

This is the same as in the last example, except we have added a NOT and some extra brackets. We know from NOT's logic gate that it has just one input.

The truth table shows us that we have just one input and the output is the opposite of the input.

As with any maths problem, we do the inside brackets first and work our way to the outside. (16 < 4) is FALSE but (121 > 45) is TRUE making the output TRUE. But then we have to NOT this, so TRUE becomes FALSE.

Take care with brackets! Always match them up to check you haven't missed one off or got an extra one when writing code. Always do the inner brackets first, combine any logic from inside brackets and then move to the outside. Brackets are very useful in Boolean algebra and in programming as they should make what you have to do and in what order much clearer.

**Q1.** State whether each of the following tests is TRUE or FALSE.

**a.** (10 > 20) OR (30 > 40)**b.** (5 < 6) AND (20 >= 10)**c.** (5 <= 10) AND (35 < 50)**d.** (3 != 3) OR (5 == 5)**e.** (7 >= 8) OR (14 != 15)**f.** NOT ((50 > 40) AND (10 > 5))**g.** NOT (5 >= 5)**h.** NOT (20 != 20)**i.** NOT ((34 > 24) OR (3 > 1))**j.** NOT ((20 < 30) AND (30 > 5))**k.** ("Fred" > "John") OR ("Cat" < "Dog")**l.** NOT (("Fred" > "John") OR ("Cat" < "Dog"))**m.** NOT (("table" > "Table") AND ("Left" < "Left"))**n.** NOT ( NOT ("up" < "down"))

**Extension task**

Write your own Boolean tests and work out the answer. Then give swap your questions with someone in your class and see if you can do each others.