CIE IGCSE | 8.1.1 Declaring and Using Variables and Constants

Lesson objective

Declare variables and constants, choose meaningful identifiers, initialise and update values, and explain how assignment affects stored data.

Learn

8.1.1 | DECLARING AND USING VARIABLES AND CONSTANTS

01 | HOW DOES A PROGRAM REMEMBER A SCORE?

Imagine a quiz game. A player begins with zero points, answers a question correctly and earns five points. The program needs to remember the score between those events. If it forgot the score after each instruction, it could not show a meaningful result.

A variable is a named storage location whose value can change during execution. We might name the quiz variable Score. The name gives instructions a way to refer to the same piece of information.

Think of a labelled container. The label is Score; the value inside might be zero, then five, then ten. The name remains the same while the stored value changes.

IDENTIFIER

Score

The name used by instructions

CURRENT VALUE

5

What the variable holds now

This is a model to help your reasoning, not a claim that all variables occupy identical physical boxes. For now, focus on the name, its permitted type and its current value.

02 | DECLARE THE VARIABLE BEFORE USING IT

In Cambridge pseudocode, a declaration introduces a variable and states its data type. A type tells us the kind of value it is intended to hold.

DECLARE Score : INTEGER

Read this as “declare a variable called Score with type INTEGER”. INTEGER means a whole number, so it is suitable for a quiz awarding whole-number points.

A declaration is not a starting score
PartMeaning
DECLAREKeyword introducing a variable
ScoreIdentifier: the variable’s name
:Separates the identifier from its type
INTEGERThe type of data the variable holds

This instruction does not say that the score is zero. It states the name and type. Until a value is assigned or supplied, do not assume the variable contains a useful default value.

Some programming languages introduce variables differently. Use the Cambridge declaration format for pseudocode answers in this course.

03 | INITIALISE IT WITH A STARTING VALUE

Initialisation assigns a starting value before it is needed. A new quiz should start with zero points, so we add a separate instruction.

DECLARE Score : INTEGER
Score ← 0

The assignment arrow points towards the variable receiving the value. Here, the value zero is stored in Score.

Declaration and initialisation answer different questions: “What is this named item and its type?” and “What value should it have at the start?” They are both important.

If you use Score in a calculation before giving it a value, you have not provided a sound starting state for the algorithm. Do not assume every numeric declaration automatically becomes zero.

04 | CHANGE A VALUE WITHOUT CHANGING ITS NAME

Assignment can also replace a value that is already stored. These instructions run in order.

DECLARE Score : INTEGER
Score ← 0
Score ← 5
Score ← 12
OUTPUT Score
Only the current value is held by this variable
Instruction completedCurrent Score
DECLARE Score : INTEGERNot yet assigned
Score ← 00
Score ← 55
Score ← 1212
OUTPUT Score12, unchanged

The output is twelve. Assignment to twelve replaces the earlier five; it does not create a second variable called Score or add twelve to five.

OUTPUT reads a value for display. It does not remove that value from the variable. To retain earlier scores as a history, a program would need additional storage, which this example does not include.

05 | ASSIGNMENT IS NOT A MATHEMATICAL EQUATION

The instruction Score ← Score + 5 can feel strange if you read it as an equation. Instead, read it as an action: calculate the right-hand side using the current value, then store the result on the left.

Score ← 7
Score ← Score + 5

First Score holds seven. The right-hand expression becomes seven plus five, which is twelve. The assignment then replaces Score with twelve.

READ

Score is 7

Use its current value

CALCULATE

7 + 5 = 12

Evaluate the expression

STORE

Score becomes 12

Replace the old value

In Cambridge pseudocode, ← means assignment. A comparison such as Score = 12 tests equality in a condition. These are different operations.

This idea underlies counters and running totals: Count increases by one per item, while Total increases by the amount being added.

06 | COPYING A VALUE DOES NOT LINK THE VARIABLES

One variable can receive another variable’s current value. That does not make their later changes automatically follow each other in this simple numeric example.

DECLARE Score : INTEGER
DECLARE SavedScore : INTEGER
Score ← 10
SavedScore ← Score
Score ← Score + 5
OUTPUT Score
OUTPUT SavedScore

SavedScore receives ten when the copy instruction runs. Score then becomes fifteen. SavedScore still holds ten because no later instruction changes it.

A copied numeric value is not a live formula
MomentScoreSavedScore
After Score ← 1010Not yet assigned
After SavedScore ← Score1010
After Score ← Score + 51510

The outputs are fifteen, then ten. Apply the same reasoning to calculations: Total ← Price * Quantity stores the result at that moment. Changing Quantity later does not recalculate Total unless another instruction does so.

07 | INPUT CAN SUPPLY A VARIABLE’S VALUE

Not every value is written directly into the algorithm. INPUT receives information from a user and stores it in a named variable.

DECLARE PlayerName : STRING
OUTPUT "Enter your name"
INPUT PlayerName
OUTPUT "Welcome, ", PlayerName

If the user enters Maya, PlayerName receives the text Maya. The final output combines the fixed greeting with that current value.

PlayerName uses STRING because a name is text. A variable can hold text or other kinds of information as well as numbers. The next lesson explores the five basic data types in detail.

Receiving input does not automatically validate it. If a name must be present or a number must be within a range, the program needs the relevant checks. This example simply demonstrates receiving and using a value.

08 | A NAME AND QUOTED TEXT ARE DIFFERENT

Quotation marks identify literal text. Without quotes, an identifier refers to the item with that name.

DECLARE Score : INTEGER
Score ← 12
OUTPUT "Score"
OUTPUT Score
OUTPUT "Your score is ", Score
The first line outputs a word; the second outputs a value
InstructionOutput
OUTPUT "Score"Score
OUTPUT Score12
OUTPUT "Your score is ", ScoreYour score is 12

A literal is a value written directly in an instruction, such as twelve or the text “Score”. A variable identifier names something whose current value can be retrieved.

Writing OUTPUT "PlayerName" prints the word PlayerName, not the user’s name. This is a common source of confusing output even when the input has been stored correctly.

09 | WHEN A VALUE SHOULD STAY FIXED, USE A CONSTANT

A quiz might award five points for every correct answer. That rule should stay fixed while the quiz runs, even though the player’s score changes. Use a constant to name that fixed value.

CONSTANT PointsPerCorrectAnswer ← 5
DECLARE Score : INTEGER
Score ← 0
Score ← Score + PointsPerCorrectAnswer

The CONSTANT statement gives PointsPerCorrectAnswer its name and value together. Unlike the variable declaration format, it does not use a colon and explicit type in this Cambridge notation.

A constant’s value must not be reassigned during execution. An instruction such as PointsPerCorrectAnswer ← 10 later in this algorithm would contradict its role as a constant.

Fixed during execution does not mean unchangeable forever. A developer can edit the constant definition before a future run if the quiz rules change. That is different from the running program updating it.

10 | VARIABLES, CONSTANTS AND LITERALS SIDE BY SIDE

Choose according to the role the value plays. Does it need to change while the solution runs, or is it a fixed rule used by the instructions?

A variable need not change in every run; it is permitted to change
ItemRole in the quizExample
VariablePlayer score changesScore
ConstantPoints awarded remain fixed during the runPointsPerCorrectAnswer
LiteralDirectly written value5 or "Correct answer"

A constant is not simply any value that happened to remain unchanged in one test. A variable called PlayerName might receive one name and keep it throughout a run, yet it is still a variable rather than a declared constant.

A constant can represent text too, such as CONSTANT WelcomeText ← "Welcome to the quiz". Numeric versus text data is a different distinction from variable versus constant.

Do not describe constants as permanent database records. Their defining property here is that the algorithm does not change their values during execution.

11 | NAMED CONSTANTS MAKE THE RULE CLEAR

Suppose an instruction says TotalCost ← Quantity * 3. It calculates a result, but the reason for three is hidden. Is it the ticket price, a conversion factor or a discount multiplier?

CONSTANT TicketPrice ← 3.00
DECLARE Quantity : INTEGER
DECLARE TotalCost : REAL
OUTPUT "How many tickets?"
INPUT Quantity
TotalCost ← Quantity * TicketPrice
OUTPUT "Cost: ", TotalCost

The name TicketPrice explains the purpose of the value. If the ticket price changes before a future run, update its definition rather than hunting through several repeated literal threes.

Assume Quantity is supplied as a valid non-negative whole number. Four tickets give a calculated total of twelve. TotalCost uses REAL because a price or later ticket-price change can include fractional amounts. This example does not specify currency formatting.

Meaningful names help you read, maintain and explain the algorithm. They reduce ambiguity, but do not guarantee the calculation or requirements are correct.

12 | CHOOSE IDENTIFIERS THAT EXPLAIN THEIR JOB

An identifier is a name used for an item such as a variable or constant. Score, TicketPrice and TotalCost explain their purpose more clearly than A, B and C in a ticket calculation.

For Cambridge pseudocode, use Pascal case: begin each word with a capital letter and join them without spaces, as in PlayerName. Identifiers use letters and digits, start with a capital letter and must not use reserved keywords.

These are Cambridge pseudocode conventions, not universal language rules
IdentifierSuitable here?Reason
TotalScoreYesDescriptive Pascal case
Player2ScoreYesBegins with a letter; later digits allowed
2PlayerScoreNoStarts with a digit
Total ScoreNoContains a space
total_scoreNoUses an underscore; not the required convention
INPUTNoReserved keyword

The specification treats identifiers as case-insensitive. Score and SCORE should not be treated as different variables. Use consistent spelling rather than trying to distinguish items by letter case.

Constants use the same identifier convention here. Do not import another language’s all-uppercase underscore style into these examples.

13 | FOLLOW A COMPLETE QUIZ-SCORE EXAMPLE

Bring declaration, initialisation, constant use and updates together. This short algorithm awards points for two correct answers already known to have occurred; it does not yet receive or check quiz responses.

CONSTANT PointsPerCorrectAnswer ← 5
DECLARE Score : INTEGER
DECLARE SavedScore : INTEGER
Score ← 0
Score ← Score + PointsPerCorrectAnswer
SavedScore ← Score
Score ← Score + PointsPerCorrectAnswer
OUTPUT "Current score: ", Score
OUTPUT "Earlier score: ", SavedScore
Current score output is 10; earlier score output is 5
Instruction completedScoreSavedScorePointsPerCorrectAnswer
Constant definition and declarationsNot yet assignedNot yet assigned5
Score ← 00Not yet assigned5
First score update5Not yet assigned5
SavedScore ← Score555
Second score update1055

The constant stays five throughout. Score changes, and SavedScore retains the copied earlier value. Check which instruction changes each item rather than assuming all the related values update together.

14 | AVOID THESE EARLY PROGRAMMING MISTAKES

Declaration mistaken for initialisation: DECLARE Total : INTEGER does not specify a starting total of zero.

Replacement mistaken for addition: Score ← 5 replaces the score, while Score ← Score + 5 adds five to its current value.

Constant reassigned: a rule that must change during execution needs a variable rather than a constant.

Quoted identifier: OUTPUT "Score" displays the word instead of the current score.

Copied value treated as linked: changing Score does not change the earlier numeric value copied into SavedScore.

Unclear or invalid name: choose an identifier that describes the job and follows the required notation.

When unsure, trace one instruction at a time. Record what has a value, what is replaced and what is merely read.

15 | EXPLAIN THE CHOICE, NOT JUST THE DEFINITION

A useful explanation is: “Score is a variable because the program updates it as points are earned. PointsPerCorrectAnswer is a constant because the points rule remains fixed during the run.”

For a named constant’s benefit: “TicketPrice explains the role of the price, and calculations use that name, therefore a future price change can be made at its definition instead of editing repeated literals.”

You should now be able to declare a variable, give it a starting value, update it, receive input and use a named constant. The next lesson explores INTEGER, REAL, CHAR, STRING and BOOLEAN so that you can choose types for different kinds of information.

MATCH THE INSTRUCTION TO ITS ROLE

Terminology

Terminology

Variable

A named storage location whose value can change during execution.

Constant

A named value that must remain fixed during execution.

Identifier

A name used to refer to an item such as a variable or constant.

Declaration

An instruction introducing a variable and specifying its data type.

Data type

The kind of data an item is intended to hold.

INTEGER

A data type for whole numbers.

REAL

A numeric type capable of containing a fractional part.

STRING

A sequence of zero or more characters.

Assignment

Storing the evaluated right-hand-side value in the named item on the left.

Initialisation

Giving a variable its starting value before it is needed.

Current value

The value an item holds at the present point in execution.

Literal

A value written directly in an instruction, such as 5 or "Hello".

Expression

Values, identifiers and operations that are evaluated to produce a result.

Input

Data supplied to the program, for example through INPUT.

Output

Information communicated by the program, for example through OUTPUT.

Pascal case

A naming style joining words with each word starting with a capital letter.

Reserved keyword

A word with a predefined role in the notation that must not be used as an identifier.

Value copy

Assigning the current value of one simple numeric variable to another without linking later updates.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which statements describe a variable?
2. What does DECLARE Score : INTEGER establish?
3. Score begins at seven. Which instruction makes it twelve?
4. Which statements about constants are correct?
5. Score is ten; SavedScore ← Score runs; Score becomes fifteen. What are the current values?
6. Score is twelve. Which outputs the number twelve?
7. Which identifiers follow these Cambridge conventions?
8. Why use a named TicketPrice constant?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Define a variable and a constant, and compare their roles.

2. Explain the difference between declaration and initialisation.

3. Show how Score changes after Score ← 7 followed by Score ← Score + 5.

4. Calculate Score and SavedScore after Score ← 10, SavedScore ← Score, Score ← Score + 5.

5. Explain why OUTPUT "Score" differs from OUTPUT Score.

6. Suggest suitable declarations and initialisation for a game score starting at zero and a fixed points-per-answer rule of five.

7. Explain one readability benefit and one maintenance benefit of TicketPrice rather than repeated literal 3.00.

8. Describe why Total Score, 2Total and INPUT are unsuitable identifiers here.

BUILD IT | A TICKET CALCULATION

A ticket costs a fixed 4.50 during a run. A user supplies a valid non-negative whole-number quantity. Declare suitable variables, define a named price constant, receive the quantity, calculate the cost and output it. Predict the cost for three tickets before revealing the sample.

Reveal one possible solution
CONSTANT TicketPrice ← 4.50
DECLARE Quantity : INTEGER
DECLARE TotalCost : REAL
OUTPUT "Enter ticket quantity"
INPUT Quantity
TotalCost ← Quantity * TicketPrice
OUTPUT "Total cost: ", TotalCost

Three tickets produce a calculated cost of 13.5, which can be displayed as 13.50 with suitable formatting. Formatting is not specified here. TicketPrice remains fixed; Quantity and TotalCost are variables. The scenario assumes valid input, so this sample does not claim to perform validation.

Extend your trace: after the calculation, Quantity becomes four without recalculating TotalCost. TotalCost still holds 13.5. Adding TotalCost ← Quantity * TicketPrice then changes it to eighteen.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for 8.1.1 Declaring and Using Variables and Constants is coming soon. Complete the matching task and written questions in your exercise book.