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
8INDEX 2
5INDEX 3
12INDEX 4
7INDEX 5
902 | 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]
| Item | Current meaning |
|---|---|
| Position | Index variable |
| Value of Position | 3 |
| Selected element | Scores[3] |
| Stored value / output | 12 |
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]
| Instruction | Position | Selected element | Output |
|---|---|---|---|
| First OUTPUT | 2 | Scores[2] | 5 |
| Second OUTPUT | 4 | Scores[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
| Expression | Meaning | Result |
|---|---|---|
| Scores[Position + 1] | Read index 3 | 12 |
| Scores[Position] + 1 | Read index 2, then add 1 | 6 |
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"
ENDIF09 | 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"
ENDIF10 | 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]
ENDIF12 | 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.