2D Arrays
2D arrays are data structures capable of storing more than one item of data (value) at a time.
Unlike a 1D array, which is best visualised as a single list of values, a 2D array looks like a table of values.
To achieve this, a 2D array is technically an array which contains further arrays.
The individual values are still called elements, and all elements must be of the same data type.
Example:
The pseudocode to declare a 2D array might look like this:
DECLARE ExamMark : ARRAY[1:10, 1:3] OF INTEGER
Our example array called ExamMark[] has ten elements where we can store three values of the same data type (in this case integers).
Arrays usually start with index numbers of 0 unless intentionally declared otherwise (as above).
Notice how we now need two indexes (i and j) to read or assign values into the array.
ExamMark[]
j | ||||
---|---|---|---|---|
1 | 2 | 3 | ||
i | 1 | |||
2 | ||||
3 | ||||
4 | ||||
5 | ||||
6 | 99 | |||
7 | ||||
8 | ||||
9 | ||||
10 |
To assign or read from a 2D array, we must refer to the array name and both index positions, e.g. ExamMark[6,2] contains 99.
It is common to use variables to represent the index values of a 2D array, e.g. ExamMark[i,j].
When a new value is assigned to an array element, it automatically replaces whatever was stored in that position previously.