CIE AS & A Level Computer Science, section 11.1 (Programming basics)
Variables and constants
- A variable is a named storage location whose value can change while the program runs.
- A constant is a named value that cannot change while the program runs.
Using a constant for a value used in several places (such as VAT) means it can be changed in one place, and the program is easier to read.
Declaring and initialising (pseudocode)
CONSTANT VATRate = 0.2
DECLARE Price : REAL
DECLARE Count : INTEGER
Price ← 50.0
Count ← 0
A constant is declared with =, not ←. Its value must be a literal (such as 0.2 or "N/A"), not a variable or an expression.
Assignment
Assignment stores a value in a variable using ←. The expression on the right is worked out first.
Count ← Count + 1
Total ← Price + Price * VATRate
Operators
| Type | Operators | Example |
|---|---|---|
| Arithmetic | + - * / |
7 / 2 is 3.5 (/ always gives a REAL) |
| Integer division | DIV |
17 DIV 5 is 3 |
| Remainder | MOD |
17 MOD 5 is 2 |
| Comparison | = <> < > <= >= |
Age >= 18 |
| Logical | AND OR NOT |
Age >= 13 AND Age <= 19 |
| Joining strings | & |
"Hi " & Name |
Precedence: brackets first, then *, /, DIV, MOD, then +, -. Use brackets to make the order clear.
There is no power operator in CIE pseudocode. (^ is used for pointers, see 13.1a.) To work out a power, multiply in a loop, or use your programming language's operator, such as Python's **.
Python
VAT_RATE = 0.2 # a constant (by convention, capitals)
price = 50.0
total = price + price * VAT_RATE
print(total) # 60.0
print(17 // 5, 17 % 5, 2 ** 3) # 3 2 8 (DIV, MOD, power)
Choosing names
Use meaningful identifiers, declare each variable with a suitable data type, and initialise variables (such as totals) before using them.
Common mistake: using = where ← is needed, and forgetting to initialise a total or counter to 0. Also, / always gives a real (decimal) result, while DIV gives the whole-number part.
Exam tip: in a declaration question, give the identifier, the data type and use CONSTANT for values that never change. Use brackets to make the order of calculation clear.
Check yourself
What is the difference between a variable and a constant?
A variable’s value can change while the program runs, but a constant’s value cannot.
Evaluate `23 MOD 5` and `23 DIV 5`.
and .
Write a statement to add 1 to the variable Count.
Count ← Count + 1.