Algorithms · Cambridge syllabus 7.2, 7.9, 8.1 · Lesson 2 of 3
Variables and Constants
A variable stores a value that can change; a constant names a value intended to remain fixed. Assignment replaces a variable’s current value with the evaluated expression. Meaningful identifiers communicate purpose.
By the end, you can
- Identify variables.
- Identify constants.
- Assign values to variables.
- Update variable values.
- Use meaningful identifiers.
Algorithm data
A variable is a named storage location whose value can change while the algorithm runs. The name identifies it, and reading the name gives whatever value it holds at that moment.
A constant is a named value fixed when the algorithm is written and never changed while it runs. VAT rate, the maximum number of pupils in a class and the value of pi are constants; a running total, a loop counter and a user input are variables.
Assignment puts a value into a variable and replaces whatever was there. Total ← 0 sets it; Total ← Total + Mark reads the current value, adds the mark, and stores the result back — which looks like an equation but is not one, and is the single thing beginners misread most often.
A constant is declared with CONSTANT, its name, an arrow and a literal value: CONSTANT VatRate ← 0.20. The value must be written out; it can never be a variable, another constant or an expression. Constants earn their place for two reasons. A number written once and named is easier to change: if VAT changes, one line changes rather than every calculation that used 0.20. And a named constant explains itself, so MaxPupils / 2 is readable where 30 / 2 is a puzzle.
Identifiers should say what the thing is. TotalMark, PupilCount and HighestScore need no comment; T, N and X need one on every line. Good names are the cheapest documentation there is, and the marks for maintainability depend on them.
Worth remembering
- A variable changes while the program runs; a constant is fixed when it is written.
- Total ← Total + Mark reads the old value, adds, and stores the result back.
- CONSTANT VatRate ← 0.20 declares a constant; its value must be a literal.
- Meaningful identifiers make a program readable without comments.
Worked example
Count ← Count + 1 first reads the old Count, adds one, then stores the new value.
Practice
Warm-up · not marked
Check your understanding
Answer in your own words, then compare with the worked answer. Nothing here is saved or scored.
Worked answer
12.
Check your method, units and explanation against it.
Marked practice
Set 1 of 4 · easiest first · Checked as you go, with the worked answer. Sign in or create a free account to save your progress.