Arrays
An array is a data structure that is capable of storing more than one item of data (value) at a time.
To achieve this, each piece of data in an array is given an index number to indicate its position.
The individual values in an array are called elements, and all elements must be of the same data type.
Example:
The pseudocode to declare an array might look like this:
DECLARE Burger : ARRAY[0:4] OF STRING
Our example array called Burger[] has five elements (slots) where we can store values of the same data type (in this case strings).
Arrays usually start with an index number of 0 unless intentionally declared otherwise.
Burger[]
0 | Zinger Tower |
---|---|
1 | Big Mac |
2 | Fillet Tower |
3 | Chicken Sandwich |
4 | Whopper |
To assign or read from an array, we simply refer to the array name and index (position) number, e.g. Burger[2] contains “Fillet Tower”.
You can use a variable instead of a literal number to represent the index position of an array, with i being a common choice e.g. Burger[i].
When a new value is assigned to an array element, it automatically replaces whatever was stored in that position previously.
Using Multiple Arrays
Using multiple arrays we can create relationships between stored data. To do this we need to ensure that the array index number is consistent for all related data.
Name[]
0 | Jenny |
---|---|
1 | Diane |
2 | Claire |
3 | Caragh |
4 | Ellie |
Score[]
0 | 1000 |
---|---|
1 | 772 |
2 | 534 |
3 | 1423 |
4 | 2425 |
Although stored across two separate data structures, in the above example we can learn that Ellie has a high score of 2425, and Claire of 534.