Counting

Counting

When we count we need to remember what number we are up to so we can add the next number.  When we were little we may have used our fingers to help us remember. Computers use variables.

A variable is a space in the computer's memory that we can store data.  We give that space a name so we can quickly get to that data.

When using variable we often need to:


So far in our programming of the microbit we have looked at input, processing and output, but we have yet to use storage!

Creating a variable

Go to the variables menu and click

'Make a Variable'

Give the variable a suitable name so you know what data the variable will hold.

Some new blocks will appear!

These blocks all say 'count' because that is the name that was given in this example, but they called anything.

Set 'count' to '0'

puts a value into the variable

change 'count' by '1'

will add the number to value already in the variable.  If the number is negative it will take it away.

'count'

is used to get the value from the variable.

Counting with Variables

The program below shows how you can use a variable to count.

It starts by assigning a value to count.  It sets the number to 0.  It then shows the number in the variable on the LEDs

When the A button is pressed, it changes the number in the variable by 1 (it adds 1 to the number). It then shows an image to show the user that it has added 1.

When the B button is pressed, it shows the number in the variable on the LEDs

Counting with variables

Watch the video below to see how to make a variable. assign a value then use it to count.

Add1.mp4

Challenge

Add and Take away!

Create a program that:

Key Words

Variable

A named place in memory where data can be stored and changed whilst a program is running.

Read more about variables.

Assigning

Putting a piece of data into a variable