Variables
Variables hold a specific type of information. Programmers use variables to hold the value of information that may change. For example, a game program can have a variable to hold the current player’s score.
Microbit variables can be numbers, strings, booleans, sprites and arrays. To use a variable, you assign a type of information it should hold. From that point forward, you can only change the value of that variable to another value of the same type.
- A number variable could hold numerical data such as the score, the year, age, etc..
- A string variable holds a string of alphanumeric characters such as a person’s name, a password, address, etc..
- A Boolean variable has only two values: true or false. For example, you might have certain things that happen only when the variable called Bonus is true.
- A sprite is a special variable that represents a single dot on the screen and holds two separate values for the row and column the dot is currently in.
- An array is another special type of variable that holds a list of multiple items.
Iterations
Certain sequence of commands are commonly repeated several times in a program, this is called iteration. Computer programmers can use a special type of code called a loop around the commands they want to repeat as a form of iteration. A loop repeats code until a certain condition is met.
There are three types of loops in Microsoft Make Code:
- repeat block – This block repeats the code n number of times.
- while block – This block runs the code as long as the condition inside of it is true.
for block – This block repeats the code n number of times, but with a variable.
As an example, let us take the last sample program from Lesson 8: Controlling individual onboard LED and use a for block loop to simplify the program. Assign coordinate y for the iteration and lit and unlit it five times. Note that the x coordinate should retain the value 2 since the value of the horizontal remains the same.