Boolean in programming

Boolean algebra is used frequently in computer programming. A Boolean expression is any expression that has a Boolean value. For example, the comparisons 3 < 5, x < 5, x < y and Age < 16 are Boolean expressions.

  • The comparison 3 < 5 will always give the result true, because 3 is always less than 5.
  • The comparison x < 5 will give the result true when the variable x contains a number less than 5, and false when it contains any number that is greater than or equal to 5. The variable x must contain a number for this comparison to make sense.
  • The comparison x < y will give the result true when the variable x contains a value that is 'less than' the value contained by the variable y. Note that in some programming languages the 'less than' operation is only defined for numbers, but in others it is defined for other data types as well.

Computer programmers use Boolean values to control selection and repetition in programs. For example, in a cinema computer system Boolean could be used to program the type of tickets people should get. Here it is written in pseudocode:

Ask the user to type in their age in whole years Store the input data in the variable Age If Age<16 Set EntranceFee = 500 Otherwise Set EntranceFee = 1000

NOT, AND, OR

Boolean expressions may combine two or more Boolean values using the operations NOT, AND and OR. This is used in many different algorithms.

For example, a cinema computer system could assess if people under 16 and over 65 are charged the concession rate. This is the algorithm in pseudocode:

Ask the user to type in their age in years Store the input data in the variable Age If Age<16 OR Age>65 Set EntranceFee = 500 Otherwise Set EntranceFee = 1000

In this example, the expression Age < 16 OR Age > 65 will give the value 'true' when the user's age is less than 16 or when it is greater than or equal to 65, otherwise it will give the value 'false'.

It is also possible to create variables that will hold Boolean values for later use.

Flowchart illustrating the variables required to complete the computer instruction

The variables in this scenario are 'Age', 'EntranceFee' and 'Concession'. 'Age' can be any integer, 'Concession' is used to hold a Boolean value and 'EntranceFee' is set according to the status of 'Concession' (500 or 1000). This can be expressed in pseudocode as follows:

IF Age<16 OR Age>65 THEN Concession IF Concession THEN EntranceFee = 500 IF NOT Concession THEN EntranceFee = 1000

The truth table for this system will be:

Age under 16?Age 65+?Concession?
YesNoYes
NoYesYes
NoNoNo
Move on to Test
next