Topic 8 · Programming
One-dimensional and two-dimensional arrays
Store lists and tables of data in arrays, use indexes, and process them with loops and nested loops.
One-dimensional arrays
An array stores many values of the same data type under one name. Each value is an element, found by its index in square brackets. Declare the lowest and highest index when you create the array.
| 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|
DECLARE Scores : ARRAY[1:6] OF INTEGER
Scores[1] <- 72
Scores[3] <- 88
OUTPUT Scores[3]Arrays and loops
Arrays and FOR loops belong together: the loop counter becomes the index, so the same code processes every element.
DECLARE Scores : ARRAY[1:6] OF INTEGER
DECLARE Index : INTEGER
DECLARE Total : INTEGER
Total <- 0
FOR Index <- 1 TO 6
INPUT Scores[Index]
Total <- Total + Scores[Index]
NEXT Index
OUTPUT "Average: ", Total / 6Two-dimensional arrays
A 2D array is a table with rows and columns. It needs two indexes: the row first, then the column. Click any cell below.
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 |
Marks[2, 3] is student 2's mark on test 3.Nested loops for 2D arrays
To visit every element, use one loop for the rows and another inside it for the columns.
DECLARE Marks : ARRAY[1:3, 1:4] OF INTEGER
DECLARE Student : INTEGER
DECLARE Test : INTEGER
DECLARE Total : INTEGER
FOR Student <- 1 TO 3
FOR Test <- 1 TO 4
INPUT Marks[Student, Test]
NEXT Test
NEXT Student
FOR Student <- 1 TO 3
Total <- 0
FOR Test <- 1 TO 4
Total <- Total + Marks[Student, Test]
NEXT Test
OUTPUT "Student ", Student, " total: ", Total
NEXT StudentKey terms
- Array
- A data structure holding many values of the same type under one identifier.
- Element
- One value stored in an array.
- Index
- The position number used to access an element.
- 2D array
- An array with rows and columns, accessed with two indexes.
Check yourself
Declare an array to hold the names of 30 students.Show answer
DECLARE Names : ARRAY[1:30] OF STRING.
In the Marks table above, what is Marks[3, 2]?Show answer
19 (row 3, column 2).
Why use an array instead of 30 separate variables?Show answer
One name holds all the values, and a loop can process every element with the same few lines of code.
Practise this skill
Use what you learned in a question, then run your answer in the studio editor.