# 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…

- 3 - 5 + 2 * 2 ^ 2 + 3 becomes 3 - 5 + 2 * 4 + 3
- 3 - 5 + 2 * 4 + 3 becomes 3 - 5 + 8 + 3
- 3 - 5 + 8 + 3 becomes 8 + 8 + 3
- 8 + 8 + 3 becomes 16 + 3
- 16 + 3 becomes 19

Work out each of the following.

# 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.