Precedence in Maths and Boolean operators
Introduction
Precedence refers to the order in which you carry out the parts of a calculation. 3 + 4 * 2 = 11, not 14 because you always do multiplication before addition. Note that multiplication and division are the same, just as subtraction is the same as addition because it is just adding a negative number
Maths operators
You may be familiar from Maths that the order in which you do a calculation depends on the following rules:
-
- Do multiplication and division first.
- Then do addition and subtraction.
This is why 3 + 4 * 2 = 11 not 14. You do have the option, however, of changing the order the calculations are done, by using brackets. Brackets have a higher order of precedence than multiplication / division and addition / subtraction.
-
- Do whatever is in brackets first.
- Then do multiplication and division first.
- Then do addition and subtraction.
So (3 + 4) * 2 = 14 not 11, because you do what is on brackets first.
2 + 4 * 4 - 1 = 17, because you do the 4 * 4 first, to get 16, then add 2 and subtract 1.
(2 + 4) * 4 - 1 = 23 because you do the 2 + 4 first, to get 6. You then multiply 6 by 4 to get 24. Finally, you subtract 1 to get 23.
Boolean operators
If you have a Boolean expression that uses a number of operators, the order of precedence is as follows:
-
- Do NOT first.
- Then do AND.
- Then do OR.
Again, brackets can be used to ensure parts of expressions are done first as they have a higher precedence.
-
- Do whatever is in brackets first.
- Then do NOT next.
- Then do AND.
- Then do OR.
For example, if you had to search through a database of books:
WHERE Subject = "Maths" OR Subject = "Physics" AND Cost < £15.00
you would find the Physics books costing less than £15.00 first, and then get those books OR Maths books in the database (because AND is done before OR). You could change the meaning of the expression though:
WHERE (Subject = "Maths" OR Subject = "Physics") AND Cost < £15.00
This would get all the Maths or Physics books first and then get those books which were under £15.00.
It is always a good idea to use brackets in programming, whether or not they are needed. They often help make your program more readable and easier to follow.