More Counting

Take a look at the program below, and try and work out what it does.

We have used all the blocks before....

Press the A button to see if your prediction was right

What do you think would happen if we changed the code in the start block to 'Set target to 5'?

Explanation of the code

(click to expand)

Here we have used a variable to store the number of times we want the loop to repeat.

In 'on button A pressed' block, we add 1 to the counter every time it goes through the loop and display the answer.


A Quick Count

Watch the video below that demonstrates how to create a counter using loops and variables

CountingTo10.mp4

Challenges

Count up to...

Adapt the program above so that when you press A it counts up to the number of times you have pressed B.

Your program should do the following:

  • When the program starts the target is set to zero
  • When you press B, add 1 to target.
  • When you press A:
    • Set the counter to zero
    • Repeat ‘target’ times. Inside the loop:
      • Add 1 to the counter.
      • Show the number in the counter


Press B any number or times.

Then press A, and the microbit will count to that number.

Count Down

Write a program that will count down from 10 to 1.

Your program should do the following:

  • Have a variable to store the startNumber
  • When the program starts, the startNumber is set to zero
  • When you press A:
    • Set the counter to startNumber
    • Repeat ‘startNumber’ times. Inside the loop:
      • Take 1 away from the counter.
      • Show the number in the counter


Press A to count down

Key Words

Variable

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

Assigning

Putting a piece of data into a variable

Loop

A programming structure that allows the code inside it to be repeated multiple times.

Iterate

To repeat