What is a variable in programming?
A variable is a named location in memory that stores a value which can change while a program runs. Each variable has a name and a data type. In National 5 Computing Science, the data types are character, string, integer, real and Boolean. Choose meaningful names so code is readable. Example: Trace the code below. SET score TO 10 SET score TO score + 5 SEND score TO DISPLAY score starts at 10, then becomes 10 + 5 = 15. Answer: The program displays 15.
Variables let a program store and update data such as scores, names or totals. In SQA National 5 Computing Science, you declare variables with an appropriate data type: character, string, integer, real or Boolean. Assignment replaces the old value with a new one, which is why a variable's value can change during execution.
Worked example
Trace: SET score TO 10, SET score TO score + 5, SEND score TO DISPLAY. What is displayed?
- Line 1: score is assigned the value 10.
- Line 2: evaluate score + 5 = 10 + 5 = 15.
- Assign the result back to score, so score = 15.
- Line 3: display the current value of score.
Answer: The program displays 15.
Want one-to-one support?
One-to-one online tuition can help you build confidence in your subject. Find a tutor who teaches your course.
Find a TutorLearn face to face in Glasgow
Prefer in-person lessons? Visit the ExpertTutor Glasgow Southside centre.
See the centre