2a - Programming Basics
All data a program uses must be stored in memory.
Each location is given a unique identifier whilst the program is running.
If the value of the data stored at this location may change as the program is running, these are called variables.
Each variable has a data type, that defines what operations can be done on the data.
For example, you can multiply two numbers together but you cannot multiply two words together. The data type tells the computer this.
Some programming languages require variables to be declared at the start of the program.
This allows the computer to allocate the necessary memory as the program starts.
Example:
dim num1 as integer dim length as float dim choice as char dim username as string dim found as boolean
Some programming languages (e.g. Python) do not need the variables declared, they work it out from the data.
A whole number
e.g. 3, 45, -435
Typically 2 or 4 bytes of memory used (16 or 32 bits)
A number with a fractional part.
e.g. 34.654, -9.5, 3.100
Typically 4 or 8 bytes of memory used (32 or 64 bits)
A single character, where a character can be any letter, digit, punctuation mark or symbol that can be typed
e.g. '4', 'a', '?', '÷'
Typically 1 byte of memory used (8 bits)
Zero or more characters, can be null (empty), one or more characters
e.g. '', 'a', 'the sun is shining!', ' '
Typically 1 byte of memory used per character
A Boolean variable has the value 'True' or 'False'
Typically 1 byte of memory used
This table shows some of the data types and the typical amount of memory each needs.
Data type | Type of data | Typical amount of memory |
---|---|---|
integer | A whole number, such as 3, 45, -435 | 2 or 4 bytes |
real/float | A number with a fractional part such as 34.456, -9.2, 4.10 | 4 or 8 bytes |
char/ character | A single character, where a character can be any letter, digit, punctuation mark or symbol that can be typed | 1 byte |
string | Zero of more characters. A string can be null (empty) | 1 byte per character |
Boolean | A Boolean variable has the value True or False | 1 byte |
In most programming languages, values are assigned to variables using an '=' sign.
x = 1 pi = 3.142 alpha = 'a' street = 'Elm Street' over18 = True
Note: x = 1 means assign the value of 1 to the variable x.
In pseudocode, we use the symbol ← to mean assignment, for example:
x ← 1