Logic: AND, OR, NOT
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A club that checks your age
- A coding club takes members only from age 11 to 16. One test cannot say both ends.
ANDisTRUEonly when both tests areTRUE.- Write the variable on each side:
Age >= 11 AND Age <= 16.
DECLARE Age : INTEGER
Age ← 14
IF Age >= 11 AND Age <= 16
THEN
OUTPUT "accepted"
ELSE
OUTPUT "no"
ENDIF
OR: either test is enough
- A bus fare is free for a child or a senior: under 5, or 65 and over.
ORisTRUEwhen at least one test isTRUE.
DECLARE Age : INTEGER
Age ← 70
IF Age < 5 OR Age >= 65
THEN
OUTPUT "free"
ELSE
OUTPUT "pay"
ENDIF
NOT flips a Boolean
NOTturnsTRUEintoFALSE, andFALSEintoTRUE.- A search that has not found the target yet is
NOT Found.
DECLARE Found : BOOLEAN
Found ← FALSE
IF NOT Found
THEN
OUTPUT "missing"
ENDIF
Watch out
Mark >= 0 AND <= 100is not a test. The second half has nothing to compare.- Parentheses make a mix obvious:
NOT (Age < 11 OR Age > 16).
Common mistakes
AND,ORandNOTare keywords. Their operands areBOOLEAN, usually from a relational test.9618putsTHENon theIFline. This course keepsTHENon the next line.
Now you try
- Each task is one decision. Write both sides of
ANDand ofOR. - Press Check answer to test it.
Read an INTEGER Age. Output accepted when it is from 11 to 16 inclusive, using AND. Otherwise output no.
Click Run to see the output here.
Read an INTEGER Age. Output free when Age is under 5 or at least 65, using OR. Otherwise output pay.
Click Run to see the output here.
Found is a BOOLEAN set to FALSE. If NOT Found, output missing.
Click Run to see the output here.