An array stores several values of the same type under one name. Each value has an index, its position, and you reach it with Name[index]. The index and the value are different things, and mixing them up is a frequent source of wrong answers.
This lesson finishes the loop skills in repetition and arrays by joining them to arrays. It follows finding a maximum, where the position and the value both appeared.
How do you read an array?
An array is declared with its bounds and type:
DECLARE Level : ARRAY[1:5] OF INTEGER
Suppose it holds these values.
| Index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Level[index] | 3 | 5 | 2 | 5 | 4 |
Level[3] is 2. The index is 3, the value is 2. A value can itself be used as an index.
Level[Level[2]] means: first work out Level[2], which is 5, then find Level[5], which is 4.
Worked example
This algorithm finds where the largest value is kept.
Pos ← 1
FOR i ← 2 TO 5
IF Level[i] > Level[Pos]
THEN
Pos ← i
ENDIF
NEXT i
OUTPUT Pos, Level[Pos]
Pos stores an index, so it is always a number from 1 to 5. Level[Pos] is the value at that index.
| i | Level[i] | Level[Pos] before | Level[i] > Level[Pos]? | Pos after |
|---|---|---|---|---|
| 2 | 5 | 3 | true | 2 |
| 3 | 2 | 5 | false | 2 |
| 4 | 5 | 5 | false | 2 |
| 5 | 4 | 5 | false | 2 |
The output is 2, 5: the index is 2 and the value stored there is 5. If the code printed i after the loop instead of Pos, it would show the loop variable, not the position of the largest value.
The mistake to watch for
A common slip is to add the index when the task asks for the values.
Mistaken code:
Total ← Total + iThis adds 1 + 2 + 3 + 4 + 5 = 15, which is the sum of the positions.
The correction is Total ← Total + Level[i], which adds 3 + 5 + 2 + 5 + 4 = 19. When you trace, write the column headings i and Level[i] separately. The two columns cannot be mixed up if both are on the page.
Check yourself
Use the array Level above.
1. What are Level[4] and Level[Level[3]]?
Show answer
Level[4] is 5. Level[3] is 2, so Level[Level[3]] is Level[2], which is 5.
2. What does this code output?
FOR i ← 1 TO 5
IF Level[i] = 5
THEN
OUTPUT i
ENDIF
NEXT i
Show answer
It outputs the indexes where the value is 5. Level[2] and Level[4] equal 5, so the output is 2 then 4. It does not output the value 5.
3. What happens if the code tries to read Level[6]?
Show answer
The bounds are 1 to 5, so position 6 does not exist. The program would stop with an error. In a trace you write “index out of bounds”.
Where this leads next
With loops, faults and arrays covered, test everything together in the repetition and arrays practice set. To watch the index and the value change on each pass, use the pseudocode trace trainer.
A teacher in Computer Science tuition can ask you to explain, line by line, what each bracketed number means in your own attempts.