If we write down a multiplication on paper, it looks like this:
3 X 3 = 9
But if we typed that in as part of our program the compiler wouldn’t know that we mean the multiplication symbol and not the letter X. Instead we use the symbol * to avoid confusion:
3 * 3
The symbol * means multiply the two numbers together. When we write down division on paper, it looks like this:
| 9 | |
| - | = 3 |
| 3 |
But if we typed this as part of our program, we would have to type a 9, start a new line, type a -, start a new line, then type a 3. To save all that work, we just use the symbol /
9 / 3
The symbol / means divide the second number by the first number. Computers naturally deal with whole numbers, and when they encounter arithmetic that results in a decimal they always round down to the nearest whole number, so:
| firstNumber | / | secondNumber | Real Answer | Computer's Answer | Remainder |
|---|---|---|---|---|---|
| 9 | / | 3 | 3 | 3 | 0 |
| 10 | / | 3 | 3.33 | 3 | 1 |
| 12 | / | 11 | 1.09 | 1 | 1 |
To get the remainder we use a special symbol, %. The first number, followed by %, followed by the second number, gives the remainder if we were to divide the second number by the first number:
10 % 5 = 0
11 % 5 = 1
If you wanted to work out a remainder in your head, you would probably have to do the division first, but computers don’t need to. They can work out a remainder at any point in the program without being told to do the division first.
Compile and run the program and note the result of the arithmetical expression
Change the expression to 4 / 2 and note the result
Change the expression to 5 / 2 and note the result
Change the expression to 5 % 2 and note the result