sciandu
Computer science

Computer science

Combining logic

Nesting AND, OR and NOT: how programs make even tricky decisions.

What you need first

Are you taking the rain jacket today? You probably think something like: if it rains AND it is cold, then yes. Your weather app thinks the same way, just in conditions: it combines several simple checks with AND, OR and NOT into one decision. You already know these three on their own. Now you will learn to nest them, because that is when programs get really smart.

Combining conditions

AND is only true when both parts are true. OR is true as soon as at least one part is true. NOT flips true and false. From these you build longer expressions: (rain AND cold) OR storm means: jacket on if it rains and is cold, or if there is a storm, no matter how warm. The parentheses show what belongs together.

Logic gate
A
B
Output
ABAND
000
010
100
111

1 AND 0 = 0

Try it: pick AND, OR or NOT, flip the inputs and follow along in the truth table. These are exactly the building blocks you assemble into longer expressions.

Who goes first?

Just like multiplication before addition, logic has an order of operations: NOT before AND before OR. So the expression NOT A AND B OR C is read as ((NOT A) AND B) OR C. If you want a different order, you need parentheses. And to fully understand a combined expression, a helps: you write down every combination of the inputs and work out the result for each row. With 2 inputs that is 4 rows, with 3 inputs already 8, because every extra input doubles the number of rows.

The trick with NOT in front

What does NOT (rain AND cold) mean? Careful, popular trap: it does not mean that it is neither raining nor cold. It only means: the combination of both is not the case. So it is not raining, OR it is not cold (or both). This transformation is the De Morgan idea: a NOT in front of parentheses moves onto both parts and turns AND into OR (and the other way around).

Exercises

0 of 6 solved

Time to try it yourself. You can't break anything, every attempt counts.

A is true, B is false. What is A AND B?

A is false, B is true. What is A OR B?

How many rows does the truth table for 2 inputs A and B have?

Put the three logic operators in the order in which an expression without parentheses is evaluated, from first to last.

  1. 1AND
  2. 2NOT
  3. 3OR

In how many of the 4 rows of the truth table is A OR B true?

NOT (rain AND cold) means: NOT rain NOT cold.

Where this leads