Data structures are formats for storing data - like arrays, records, and files.
An array is a data structure that can store a group of data of the same type under a single identifier.
Each piece of data within an array is called an element. Each element can be accessed by its index (position) in the array.
Example 1 shows how to create and manipulate arrays in pseudo-code.
Example 1
Use square brackets to define an array
names ← ["Adam", "Bob", "Charlie", "Daniel"]
Elements in arrays can be retrieved just like characters in strings
OUTPUT names[2]
>>> "Charlie"
Remember: indexing starts at 0
Elements can be changed as well
names[1] = "Ben"
OUTPUT names
>>> ["Adam", "Ben", "Charlie", "Daniel"]
Just like with strings, LEN returns the length of an array
OUTPUT LEN(names)
>>> 4
Two-dimensional (2D) arrays are arrays of arrays.
Example 2 shows the manipulation of a 2D array.
Example 2
Five students' Maths and English scores are shown in this 2D array
Each array inside this 2D array contains a certain student's two test scores
scores ← [[9, 15],
[18, 8],
[12, 14],
[13, 7],
[10, 17]]
Retrieve the fourth student's scores
OUTPUT scores[3]
>>> [13, 7]
Retrieve the second student's first score
OUTPUT scores[1][0]
>>> 18
Get the length of the 2D array
OUTPUT LEN(scores)
>>> 5
Get the length of the first element
OUTPUT LEN(scores[0])
>>> 2
Can you think of other uses for 2D arrays?
Storing the pixel data of images, board games where the board is a grid, and much more.