Think about the last time you needed to perform long division — did you write it out on paper or reach for a calculator? We can actually write computer programs that perform calculations for us. In fact, that was their original purpose!
If we want to write a program that performs calculations, we need to use arithmetic operators. They include addition (
+), subtraction (
-), multiplication (
*), and division (
- Addition adds an amount to a number:
2 + 3 = 5
- Subtraction takes away an amount from a number:
10 - 3 = 7
- Multiplication takes a number and repeats it a specified number of times:
5 * 2 = 10
- Division takes a number and divides it by another number:
15 / 3 = 5
How does this work in real life? Let’s say we need to buy some apples for the fruit salad recipe. The recipe calls for six apples, but we can only find bags of five. If we buy just enough bags for your recipe, how many extra apples will you have?
Since one bag isn’t enough, we need to buy two bags with five apples each, which would equal 10. Then, we’d subtract the six apples that we need for our recipe to find our answer:
apples = 5 my_apples = apples * 2 answer = my_apples - 6
If we were to print out
answer, it would equal
You may notice that unlike in math class, we put the “answer” on the left-hand side of the equals sign, rather than to the right. That’s because we’re saving the value of our answer to a new variable! So,
answer are all variables.
Let’s calculate how many apples we need for our fruit salad!
The recipe says that for a fruit salad that serves 2-4 people you will need four apples. But you’re making a fruit salad for a party, so you need to double the recipe. Use the buttons to calculate the correct amount of apples to use in the fruit salad.
Start by selecting a number of apples and clicking the Add button. Now try selecting a different number and using the other operations!