Fundamentals of Programming: Boolean operators
You might have already covered a lot of boolean logic in Unit 2. Boolean logic is essential for anyone wanting to program. For example, you will end a game if it is true
that the time is up.
if timeup = true then
blowwhistle()
end if
We might want to use more complex boolean logic, for example if the time is 16:00 or before 9:00, it is the holiday or it is the weekend, then you don't have to go to school:
dim holiday, weekend as boolean
'...
If now > 16 OR now < 9 OR holiday OR weekend Then
noschool()
Else
gettoclass()
End If
Notice here how we didn't say, holiday = true
, we just said holiday
, if something is true, then comparing it to true will also return true (phew!), so there really is no need check and see. Programming languages allow you to compare boolean values using a variety boolean operators that you probably know and love:
NOT | AND | OR | XOR | ||
---|---|---|---|---|---|
T | T | F | T | T | F |
T | F | F | F | T | T |
F | T | T | F | T | T |
F | F | T | F | F | F |
If you have been writing a lot of truth tables (you have Wittgenstein to blame), get VB.NET to do if for you!
console.writeline("A|B||A.B|A+B|AxB")'write the heading
for A = 0 to 1
for B = 0 to 1
console.write(A & "|" & B & "||")
console.write(A AND B & "|")
console.write(A OR B & "|")
console.write(A XOR B & "|")
console.writeline()
next
next
Exercise: Boolean Operators Answer: Answer: Answer: |
for A = 0 to 1
for B = 0 to 1
for C = 0 to 1
console.write(A & "|" & B & "|" & C & " = ") 'write the heading
console.write(A AND B AND C & "|")
console.write(A AND B OR C & "|")
console.write(A OR B AND C & "|")
console.write(A OR B OR C & "|")
console.writeline()
next
next
next