Mathematical Expressions
| English | Chinese | Pinyin |
|---|---|---|
| arithmetic | 算术 | suàn shù |
| arithmetic expression | 算术表达式 | suàn shù biǎo dá shì |
| order of operations | 运算顺序 | yùn suàn shùn xù |
| modulus | 取模 | qǔ mó |
| remainder | 余数 | yú shù |
| integer | 整数 | zhěng shù |
Doing arithmetic in a program
- Programs often do arithmetic 算术.
- An arithmetic expression 算术表达式 combines numbers with operators: $+$, $-$, $\times$, $\div$.
- The result is usually stored in a variable for later, e.g. $\text{area} \leftarrow \text{length} \times \text{width}$.
- To get the right answer, you must apply the operators in the right order.
Apply the order of operations
Multiplication and division bind tighter than addition and subtraction, and equal-rank operators go left to right. Evaluate one step at a time.
What is 2 + 3 × 4?
Multiplication first: 3 × 4 = 12, then 2 + 12 = 14.
What is (2 + 3) × 4?
Brackets first: 2 + 3 = 5, then 5 × 4 = 20.
Order of operations
- A computer follows the order of operations 运算顺序 — the same rules as maths.
- Do multiplication and division before addition and subtraction.
- Work left to right for operators of equal rank; do anything in brackets first.
- So $2 + 3 \times 4 = 14$ (not 20); writing $(2 + 3) \times 4$ forces the addition first, giving 20.
What is 17 MOD 5 (the remainder)?
17 ÷ 5 is 3 remainder 2, so 17 MOD 5 = 2.
How can a program test whether a number n is even?
An even number leaves no remainder when divided by 2.
The modulus operator
- The modulus 取模 operator (
MOD) returns the remainder 余数 of integer division. - For example $17 \bmod 5 = 2$, because $17 \div 5$ is 3 with 2 left over.
- Modulus is handy for tests: a number is even when $n \bmod 2 = 0$.
- It comes up constantly — cycling through positions, checking divisibility, and more.
Evaluate 10 + 6 ÷ 2 × 3.
6 ÷ 2 = 3, then 3 × 3 = 9, then 10 + 9 = 19.
Dividing two integers can give a decimal, such as 7 ÷ 2 = 3.5.
Some languages give 3.5; others do integer division and give 3.
Integer vs decimal
- Think about integer 整数 versus decimal results.
- Adding two integers gives an integer, but division can give a decimal: $7 \div 2 = 3.5$.
- Some languages treat $7 \div 2$ as integer division and give $3$ — know which you get.
Evaluate $10 + 6 \div 2 \times 3$. Division and multiplication first, left to right: $6 \div 2 = 3$, then $3 \times 3 = 9$. Now add: $10 + 9 = 19$.
An arithmetic expression must follow the order of operations: brackets, then $\times \div$, then $+ -$, left to right — so $2 + 3 \times 4 = 14$. The modulus operator gives the remainder ($17 \bmod 5 = 2$), great for even/odd tests. Watch integer vs decimal division ($7 \div 2 = 3.5$ or $3$).