Variables are used in nearly every single computer program. They are an essential concept and can be used and manipulated using many different techniques. The following spider diagram summarises the key computing concepts linked to the use of variables in procedural programming:
Terminology:
Variables vs. Constants
Variables are used to store a value that can be changed within the program (as opposed to constants which remain the same throughout the program).
Identifier
Identifier: the name given to a variable: e.g. score, numberOfLives.
Data Types
Data Type: A variable has a data type such as:
- Integer
- Real/Float
- Boolean
- String
Declaring a variable
Declare: Some programming languages require variables to be declared first before they can be used. When declaring a variable you give it an
identifier (and a
data type for some languages) e.g.
int score
Depending on where in your code you declare a variable will have an impact on its scope.
Scope of a variable
Scope of a variable: the extent of a program in which the variable is visible/accessible.
A variable which is declared within a subprogram (e.g. procedure or function) is only available within this subprogram. It is a local variable.
A variable which is declared outside any subprograms becomes accessible to code written anywhere in the program. It is a global variable.
Initialising a variable
Initialise: To give/
assign a variable its
first value which can be changed later on in the program. e.g.
score = 0
Assigning a value
Assign: To give or change the value of a variable, using the assignment operator (=) e.g.
numberOfLives = 3
Casting
Casting: to convert/change the data type of a variable
e.g. in Python using functions such as int(), str(), float().
Incrementing
Increment: To increase the value a variable by a value (e.g. 1). e.g.:
score += 1
Decrementing
Decrement: To decrease the value a variable by a value (e.g. 1) e.g.
timer -= 1
List and Arrays
List and arrays:
Some more complex data structures such as lists and arrays enable you to store multiple values in a single variable.
e.g.
daysOfTheWeek=[“Monday”,”Tuesday”,“Wednesday”,”Thursday”,”Friday”]
Parameter passing
Passing parameters by value or by address/reference: You can pass a variable or its value to a subroutine (function or procedure). This is done either by value (in this case the value of the variable will not change outside the subroutine) or by address/reference (in this case the subroutine may change the value of the variable).