CIE IGCSE | 8.2.2 Array Indexes and Variables as Indexes

Lesson objective

Evaluate literal, variable and expression-based indices, distinguish positions from values, and trace safe reads and writes in one- and two-dimensional arrays.

Learn

8.2.2 | ARRAY INDEXES AND VARIABLES AS INDEXES

01 | ONE INSTRUCTION CAN SELECT DIFFERENT SCORES

A quiz stores five scores in an array. A user selects a player number, and the program must display that player’s score. Writing five separate output instructions would be unnecessary.

An index is an INTEGER identifying an array element’s position. When a variable supplies the index, its current value chooses the position at the moment the instruction runs.

In this lesson Scores is declared as ARRAY[1:5] OF INTEGER and contains eight, five, twelve, seven and nine. All five elements have already been assigned. Keep this starting state in mind when following the traces.

INDEX 1

8

INDEX 2

5

INDEX 3

12

INDEX 4

7

INDEX 5

9

02 | INDEX VARIABLE, POSITION AND STORED VALUE

Position is an ordinary INTEGER variable. If it holds three, Scores[Position] refers to Scores[3], whose stored value is twelve. There are three roles to distinguish: the variable name Position, its current value three, and the selected element’s value twelve.

The OUTPUT reads twelve but leaves Position at three. It does not make the index equal to the score. The array element also remains twelve.

DECLARE Position : INTEGER
Position ← 3
OUTPUT Scores[Position]
The position is not the content
ItemCurrent meaning
PositionIndex variable
Value of Position3
Selected elementScores[3]
Stored value / output12

03 | A LITERAL INDEX SELECTS A FIXED POSITION

A literal is a value written directly in the code. Scores[3] uses the literal index three, so that expression selects the same position whenever it is evaluated.

Scores[Position] uses a variable index, so a later change to Position can change which element is selected. It is not necessary to rename the array or change the output instruction.

Both forms use square brackets. The word Position is not an array label stored in the cell: it tells the program to use that variable’s current numeric value.

Position ← 2
OUTPUT Scores[Position]
Position ← 4
OUTPUT Scores[Position]
Same expression, different current index
InstructionPositionSelected elementOutput
First OUTPUT2Scores[2]5
Second OUTPUT4Scores[4]7

04 | CHANGING THE INDEX DOES NOT MOVE DATA

Position ← Position + 1 changes the index variable. It does not increase a score, shift the array or move the selected element’s value.

Starting at index two, increasing Position selects index three on the next read. The outputs are five and twelve. The five stays at index two.

To increase an element’s value, assign to Scores[Position]. To choose another element, assign to Position. Read the left-hand side carefully: it identifies what changes.

Position ← 2
OUTPUT Scores[Position]
Position ← Position + 1
OUTPUT Scores[Position]

05 | AN INDEX EXPRESSION IS EVALUATED FIRST

An expression combines values and operations to produce a result. An index expression must produce an INTEGER within the array’s bounds.

With Position equal to two, Scores[Position + 1] selects index three. The addition happens to determine the index, not to increase the stored score. The output is twelve and Position remains two.

Compare Scores[Position] + 1: that selects index two first and then adds one to its value, giving six. Moving the + 1 inside or outside the brackets changes the meaning.

Position ← 2
OUTPUT Scores[Position + 1]
OUTPUT Scores[Position] + 1
Bracket placement decides whether arithmetic affects the position or the data
ExpressionMeaningResult
Scores[Position + 1]Read index 312
Scores[Position] + 1Read index 2, then add 16

06 | TRACE WRITES USING A VARIABLE INDEX

A variable index can select a destination as well as a source. When Position is four, Scores[Position] ← 10 replaces the value at index four.

Position stays four because it is not the assignment target. Scores[Position] ← Scores[Position] + 2 then updates that same element from ten to twelve.

Other positions are unchanged. Writing an element does not append another item or change the array’s declared size.

Position ← 4
Scores[Position] ← 10
Scores[Position] ← Scores[Position] + 2
OUTPUT Position
OUTPUT Scores[Position]

07 | KEEP A COPIED VALUE SEPARATE FROM AN INDEX

SelectedScore ← Scores[Position] copies the selected score into another variable. Changing Position afterwards changes what future array accesses select; it does not update SelectedScore.

With Position initially two, SelectedScore receives five. Position then becomes three. The final outputs are five and twelve because the first uses the earlier copy and the second performs a fresh access.

A variable is not a live formula linking itself to whichever element is currently selected.

DECLARE SelectedScore : INTEGER
Position ← 2
SelectedScore ← Scores[Position]
Position ← 3
OUTPUT SelectedScore
OUTPUT Scores[Position]

08 | CHECK THE EVALUATED INDEX AGAINST THE BOUNDS

For ARRAY[1:5], a valid index must be an INTEGER from one to five inclusive. An expression based on an in-bounds variable can still produce an invalid index.

If Position is five, Position + 1 is six. Therefore Scores[Position + 1] is invalid even though Scores[Position] is valid. Check the index expression you actually plan to use.

The guard below assumes Position is INTEGER and every score has been assigned. It permits a next-position access only when Position is one through four.

IF (Position >= 1) AND (Position < 5)
  THEN
    OUTPUT Scores[Position + 1]
  ELSE
    OUTPUT "There is no next element for this position"
ENDIF

09 | A USER CAN SUPPLY AN INDEX

INPUT PlayerNumber receives a value to be used as an index. The next instruction must not access the array until that index has passed its bounds check.

This example assumes the supplied input is already an INTEGER. A bounds check alone does not convert arbitrary text or make a fractional input suitable for indexing.

Rejected input takes the ELSE route, so no invalid element is read. Valid input selects one already-initialised score.

DECLARE PlayerNumber : INTEGER
OUTPUT "Enter a player number from 1 to 5"
INPUT PlayerNumber
IF (PlayerNumber >= 1) AND (PlayerNumber <= 5)
  THEN
    OUTPUT Scores[PlayerNumber]
  ELSE
    OUTPUT "Player number is outside the array"
ENDIF

10 | EXPLORE POSITION PLUS AN OFFSET

An offset is an amount added to a starting position. The demo evaluates Scores[Position + Offset]. Change either value and follow the three stages: calculate the index, check the bounds, then read the stored value.

Controls deliberately allow combinations producing an out-of-bounds index. Those combinations show a refused access, rather than reading a non-existent score. A valid evaluated index can result from a starting Position outside the array; it is the final index expression that determines this access.

11 | ZERO-BASED ARRAYS NEED DIFFERENT INDICES

ARRAY[0:4] has five elements, but index zero is its first and index four its last. An index variable’s intended meaning must match the declaration.

If a screen numbers choices one through five while the array uses zero through four, an explicit mapping can subtract one from the choice. A displayed choice three then selects array index two.

Validate the displayed choice before conversion and access. Do not subtract one automatically from every array index: one-based arrays do not need this mapping.

DECLARE Names : ARRAY[0:4] OF STRING
DECLARE Choice : INTEGER
DECLARE Index : INTEGER
// All Names elements are assumed to have been assigned.
IF (Choice >= 1) AND (Choice <= 5)
  THEN
    Index ← Choice - 1
    OUTPUT Names[Index]
ENDIF

12 | TWO-DIMENSIONAL ARRAYS USE TWO INDEX VALUES

For ScoresGrid : ARRAY[1:3, 1:4] OF INTEGER, Student and Test can choose one cell. The first variable selects the student row, and the second selects the test column.

With Student two and Test three, ScoresGrid[Student, Test] selects [2,3]. Both evaluated indices must satisfy their own dimension’s bounds.

Changing Test alone selects another column in the same row. Changing Student alone selects another row in the same column. Index order is part of the program’s meaning.

DECLARE Student : INTEGER
DECLARE Test : INTEGER
Student ← 2
Test ← 3
OUTPUT ScoresGrid[Student, Test]

13 | A LOOP COUNTER CAN BE THE INDEX

A FOR loop naturally supplies consecutive index values. Position takes one, two, three, four and five, so the same expression visits every element.

This process is called traversal: visiting elements in a planned order. The loop counter identifies each position; the array access supplies that position’s stored value.

The counter and array must use matching bounds. Starting at zero would produce an invalid first access for this one-based Scores array.

FOR Position ← 1 TO 5
  OUTPUT "Position ", Position, ": ", Scores[Position]
NEXT Position

14 | DISTINCT SOURCE AND DESTINATION INDICES

A copy can use two different index variables. Source equal to two and Destination equal to four means Scores[Destination] ← Scores[Source] copies five into index four.

The variables stay two and four. The source remains five. The destination’s previous seven is replaced by five. Nothing is moved or removed from the source.

Check both indices before copying. A valid destination does not make an invalid source safe, and the source must contain an assigned value.

DECLARE Source : INTEGER
DECLARE Destination : INTEGER
Source ← 2
Destination ← 4
Scores[Destination] ← Scores[Source]

15 | TRACE IN THE RIGHT ORDER

For each array access, first record the current index variables. Evaluate any arithmetic inside the brackets. Check each evaluated index against the declaration. Then read or write the selected element.

A useful explanation is: “Position is two and Offset is one, so the evaluated index is three. Three is within the bounds one to five, therefore Scores[3] is accessed and its value twelve is read.”

Avoid changing an index variable when you mean to change data, confusing Scores[Position + 1] with Scores[Position] + 1, or checking only part of a two-dimensional index pair.

The next lesson develops reading and writing array values with loops.

MATCH THE INDEX EXPRESSION TO ITS ROLE

Terminology

Terminology

Index

An INTEGER selecting an array element’s position.

Index variable

An INTEGER variable whose current value selects a position.

Literal index

An index value written directly in the code.

Index expression

An expression evaluated to an INTEGER inside array brackets.

Element value

The data stored at a selected position.

Offset

An amount added to a starting position.

Evaluated index

The final INTEGER result used to select an element.

Lower bound

The first permitted index in a dimension.

Upper bound

The last permitted index in a dimension.

Bounds check

A test of whether an index falls within the declared limits.

Out-of-bounds access

An attempted read or write outside the permitted positions.

Zero-based array

An array whose first index is zero.

One-based array

An array whose first index is one.

Index mapping

Converting a displayed choice or other value into the corresponding array position.

Element assignment

Writing a value at an indexed position.

Value copy

Storing the current source value elsewhere without linking later changes.

Index pair

Two indices selecting one 2D array element.

Traversal

Visiting elements in a planned order, often with a loop counter.

Questions

Questions

CHECK YOUR UNDERSTANDING

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

1. Position is three and Scores[3] is twelve. Which are correct?
2. Position is two in the original array. Which are correct?
3. Position ← Position + 1 does what?
4. For ARRAY[1:5], which Position values safely allow access at Position + 1?
5. SelectedScore copies Scores[2] equal to five, then Position changes to three. Which are correct?
6. Displayed Choice three maps to a zero-based five-element array using Choice - 1. What is the array index?
7. Which are required for a safe 2D access?
8. Copying Scores[Source] into Scores[Destination] does which?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Explain the roles of Position and Scores[Position] when Position is three and the selected score is twelve.

2. Compare Scores[Position + 1] with Scores[Position] + 1 for Position two in the original array.

3. Explain why changing Position does not move an array value.

4. Trace Position ← 4, Scores[Position] ← 10, Scores[Position] ← Scores[Position] + 2.

5. Explain why checking Position <= 5 is insufficient before Scores[Position + 1].

6. Demonstrate mapping displayed choice three to ARRAY[0:4].

7. Describe how two variable indices select a 2D element.

8. Explain why a FOR counter is useful as an index.

BUILD IT | SELECT THE NEXT VALUE

Declare Values : ARRAY[1:4] OF INTEGER and assign ten, twenty, thirty and forty. Receive a valid INTEGER Position. Before accessing Values[Position + 1], check that the evaluated index will be within one to four. Output the next value when valid, or a suitable message otherwise. Test Position one, three, four and zero.

Reveal one possible solution
DECLARE Values : ARRAY[1:4] OF INTEGER
DECLARE Position : INTEGER
DECLARE NextIndex : INTEGER
Values[1] ← 10
Values[2] ← 20
Values[3] ← 30
Values[4] ← 40
OUTPUT "Enter a starting position"
INPUT Position
NextIndex ← Position + 1
IF (NextIndex >= 1) AND (NextIndex <= 4)
  THEN
    OUTPUT Values[NextIndex]
  ELSE
    OUTPUT "Evaluated index is outside the array"
ENDIF

Positions one and three produce twenty and forty. Position four evaluates to index five and is rejected. Position zero evaluates to index one and reads ten: this task validates the resulting index only. If the application requires Position itself to be an existing array position, add that requirement explicitly, which would reject zero.

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.2.2 Array Indexes and Variables as Indexes is coming soon. Complete the matching task and written questions in your exercise book.