Tuesday, 11 February 2014
How computers do Math - Arithmetic Operators Priority in C++
In basic math algebra where we have formulas with multiple arithmetic operations taking place in C++ ( and in everyday math ) we have rules on execution priority, meaning that C++ decides which operation to do first whether its addition or multiplication. When a math formula is being executed with multiple arithmetic operations taking place multiplication and division have higher priority over all, then comes addition and substraction. In the examples below you will see how computers choose which portion of the given formula to execute first, till it completes.
If a = 5, b = 10 and c = 2 calculate the given formula below
y = 3 * a + b / c - 2
In this basic formula we have all of the arithmetic operators taking place. The very first thing computers will try to solve is multiplication as we said, so in this given example the computer will firstly calculate 3 * a then right after it will calculate b / c. Since there are no more multiplication or division operators in this formula, the computer will take the result of the first calculated portion 3 * a and the result of the second calculated portion b / c and will do addition upon these. Below i have written the steps the computer would take to solve this problem.
Step1: 3 * a = 3 * 5 = 15
and since a = 5 we know that 3 * 5 = 15
Step2: b / c = 10 / 2 = 5
and since b = 10 and c = 2 we know that 10 / 2 = 5
Now since multiplication and division are done the computer takes the result from the first step and the result from the second step and does addition
Step3: Step1 + Step2 = 15 + 5 = 20
where Step1 + Step2 are the results from the steps respectively. And by doing addition from these two steps we achieve 20 as a result.
Step4: Step3 - 2 = 20 - 2 = 19
where Step3 is the result of the addition of Step1 and Step2. We substract 2 from Step3 and we have 18.
This is how computers break formulas into pieces and give priority based on rules to different operators. Its important to keep this in mind while programming large projects where we can have multiple calculations with different types of operators taking place, since the results can be different if we swap places of operators by mistake. And if we want precision in our calculations it is of good practice to put operations with higher priorities in parentheses. To clarify your mind take this example and translate it into actual C++ code and execute it to see the results. Do some experiments by swapping operators or adding more to see how the result will change based on priority rules.