CPU arithmetic

Calculations

A CPU has circuits that can work out that 2 + 3 is 5, and that 6 – 4 is 2.

Another one:

2 + 3 * 4

Recall that * is a splat. It means multiply.

+, -, and * are numeric operators. Here are numeric operators you'll use in this course:

+ Add, like 2 + 9
Subtract, like 2 – 9
* Multiply, like 2 * 9
/ Divide, like 2 / 9
^ Raise to a power, like 3 ^ 3 (that's 27)
Unary minus, like -3 (that's negative 3)
2 + 3 * 4

… is a numeric expression. That is, a calculation that works out a number.

You might think that the expression…

2 + 3 * 4

…works out to 20. 2 + 3 is 5, and 5 * 4 is 20. But actually:

2 + 3 * 4 is 14

That's because the CPU doesn't use the operators from left to right. Instead, some operators have a higher precedence than others. The CPU does * before it does +. So it's 3 * 4 is 12, and 2 + 12 is 14.

If you wanted the CPU to do the + first, add parentheses:

(2 + 3) * 4 is 20

Here are the numeric operators again, in precedence order:

() CPU does anything in parens first.
Unary minus, like -3 (that's negative 3)
^ Raise to a power, like 3 ^ 3
* and / Multiply and divide have equal priority, done left to right.
+ and - Add and subtract have equal priority, done left to right.

The operators in…

3 - 5 + 2 * 2 ^ 2 + 3

… would be done in this order…

  1. 3 - 5 + 2 * 2 ^ 2 + 3 becomes 3 - 5 + 2 * 4 + 3
  2. 3 - 5 + 2 * 4 + 3 becomes 3 - 5 + 8 + 3
  3. 3 - 5 + 8 + 3 becomes -2 + 8 + 3
  4. -2 + 8 + 3 becomes 6 + 3
  5. 6 + 3 becomes 9
h1. Your turn

Work out each of the following.

Fill in the blank

Expression's value 1

What does this work out to?

11 + 3 - 2

Your answer:

Fill in the blank

Expression's value 2

What does this work out to?

4 + 16 / (4 + 6 - 2) * 2

Your answer:

Fill in the blank

Expression's value 3

What does this work out to?

(2 + 1) ^ (1 + 6 / (7 - 1))

Your answer:

Fill in the blank

Expression's value 4

What does this work out to?

2 + 2 * -3 + 10 / 5

Your answer:

Fill in the blank

Expression's value 5

What does this work out to?

10 * 2 - 2 ^ 2 * 3

Your answer:

Fill in the blank

Expression's value 6

What does this work out to?

2 + 9 / 3 ^ 2 - 2

Your answer:

Summary

The evaluator is part of the CPU. It can do arithmetic. It understands operators, like +, -, and *. Some operators have precedence over others. Use parens to change execution order.