Computer programs use variables to store information.
Variables could be used to store the score in a game, the number of cars in a car park or the cost of items on a till. They work in a similar way to algebra, where a letter in your code can stand for a number.
What can be stored as variables?
Lots of things can be stored as variables. Most people think of variables as numbers. They can be but they can also store text or values such as ‘true’ and ‘false’.
Variables in computer games
If you were programming a computer game, you could make a variable called ‘score’. This would store information about the number of points you have won during a game.
When the character in your game collects a coin or piece of treasure, you could tell the program to increase the variable ‘score’ by one. As you collect points through the level this variable will keep changing.
What do we use variables for?
Variables are needed to run all but the most simple computer programs.
As a program runs, it needs to hold information in its memory. This may be a number, the answer to a question or something else.
Variables allow us to store, change and access this information as the program runs.
To make a simple program that displays your name, you could program the computer to:
- Ask for your name.
- Store that answer as a variable called ‘YourName’.
- Display “Hello” and the string stored in the variable called ‘YourName’.
How are variables used in the real world?
In a computer game, things like lives and health are variables that constantly change. If you make a mistake you lose health or a life. But you can also gain lives and health by collecting items.
A supermarket till could use variables to store information about all the items you buy. As more items are scanned the variable’s total would increase. This value will then be used to calculate how much you need to pay for your shopping.
The program controlling the automated barriers in a car park could use variables to count cars in and out. These can then be used to see if there is any space to let more cars in.