Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 2.8 Order of Operations

When more than one operator appears in an expression the order of evaluation depends on the rules of precedence. A complete explanation of precedence can get complicated, but just to get you started:
  • Multiplication and division happen before addition and subtraction. So 2 * 3 - 1 yields 5, not 4, and 2 / 3 - 1 yields -1, not 1 (remember that in integer division 2/3 is 0).
  • If the operators have the same precedence they are evaluated from left to right. So in the expression minute * 100 / 60, the multiplication happens first, yielding 5900 / 60, which in turn yields 98. If the operations had gone from right to left, the result would be 59 * 1 which is 59, which is wrong.
  • Any time you want to override the rules of precedence (or you are not sure what they are) you can use parentheses. Expressions in parentheses are evaluated first, so 2 * (3 - 1) is 4. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even though it doesn’t change the result.
Listing 2.8.1. Observe the output of the code to see how the placement of parentheses can change the result of a calculation.

Checkpoint 2.8.1.

Checkpoint 2.8.2.

The following three exercises will walk you through an example of the rules of precedence. Answer the questions in order to check what you remember about the order of operations!

Checkpoint 2.8.3.

Checkpoint 2.8.4.

Checkpoint 2.8.5.

1 + 5 is the only operation remaining. I’m not going to ask you any questions about it. However, it’s important that you can wrap you head around the fact that the + operator appeared first in the calculation, but it was the last operator to be evaluated. The order of operations can be kind of confusing at times, but I think you’ve got a good grasp of the concept!
You have attempted 1 of 7 activities on this page.