science tinker

Logic to code: from a truth table to a program

Write a rule with named inputs, like “(door AND dark) OR alarm”, or switch to the truth table and tick when the output should be 1. You get the truth table, the simplest version of the rule, and a ready-to-run program in the language you choose.

Examples:

From a rule to a program

Many programs make decisions from yes-or-no inputs: is the door open, is it dark, is the button pressed? A logic statement combines them with AND (both must be true), OR (at least one), NOT (the opposite) and XOR (exactly one of two). A truth table lists every combination of inputs and the output for each: with n inputs there are 2n rows.

Writing it in code

Every language has the same three ideas with different symbols. C, C++, Arduino, Java and JavaScript use && for AND, || for OR and ! for NOT; Python uses the words and, or and not. AND is done before OR, just as × comes before +, so a || b && c means a OR (b AND c). Add brackets when in doubt. For XOR of two true/false values, “not equal” works everywhere: a != b.

Simplifying

Different statements can give the same truth table. The tool finds the simplest sum of products with the Quine–McCluskey method, the same as a Karnaugh map: for example, A·B + A·B′ is just A. A simpler condition is easier to read, runs a little faster and needs fewer logic gates in hardware.

Try it on a board

The Arduino sketch reads one push button per input (with the internal pull-up, so a pressed button reads LOW) and lights the built-in LED on pin 13 when the output is true. Build it in the microcontroller simulator and test every row of the truth table.

Questions students ask

How do you write AND, OR and NOT in Python?

Python uses the words and, or and not, for example: if door and not locked: ... while C, Arduino and JavaScript use &&, || and !.

How do you turn a truth table into an expression?

For each row where the output is 1, write the inputs joined by AND (using NOT for inputs that are 0), then join those terms with OR; simplifying with Boolean algebra or a Karnaugh map then gives a shorter expression.

Which comes first, AND or OR?

AND is evaluated before OR in C, Arduino, Python and JavaScript, so a OR b AND c means a OR (b AND c); use brackets to make the order clear.

Check yourself

3 quick questions. Tap an answer to see if you are right.

1. How is “A and not B” written in C or Arduino?

2. How many rows does a truth table with 3 inputs have?

3. Which is the same as NOT (A OR B)?

Related

More computer science

Know someone who needs this?

It’s free for every student. Send it to your class group chat.

Updated · Free, no sign-up ·

Connected tools

The same idea from another angle, across the site.