Adding Numbers

Adding Numbers

We have used variables to store numbers, and we have used the Change block to add or take a number from the variable, but we can do more interesting maths using our normal arithmetic operators (maths symbols).

Arithmetic Operators

In the program below you can see the ADD block has been used to add the numbers 3 and 5 and the answer is assigned to the variable 'Total'.

Press A to see the micro:bit add 3 and 5

Adding Variables

We don't just have to put numbers in the maths blocks, we can also use variables, so it is possible to add to variables together.

Total = A + B

  • Press A to see the value in variable 'A'
  • Press B to see the value in variable 'B'
  • Press A+B to add the variables together and see the result.

Using The Add Operator

Watch the video below that demonstrates how to use the add operator to add numbers and variables

microbit add block.mp4

Another Way of Counting

By using the arithmetic operator instead of the 'change variable' block, we can count by adding 1 to the value of count.

count = count + 1

This works because the micro:bit because it looks and calculates what is on the left hand side of the equals before it looks at where it is going to put the answer.

It goes and fetches the value currently in the variable count, adds 1 to it, and then goes and puts the answer back in the variable count.

Count = Count + 1

Press A to add 1 to count

Watch the video below that demonstrates how to count using the add block

microbit counting 2.mp4

Challenge

Total = CountA + CountB

Create a program that:

  • When you turn it on, sets 3 variables (countA, countB and total) to zero
  • When you press A, adds 1 to countA and shows the result.
  • When you press B, adds 1 to countB and shows the result.
  • When you press A+B:
    • Sets the total to countA + countB
    • shows the result

Example Solution

Key Words

Arithmetic Operator

A symbol used to indicate a type of calculation to be carried out (e.g +, -, /, *)