Data structures and arrays
A data structure is a way of organising related data so it can be stored and used efficiently. Choosing the right one makes a program simpler and faster.
An array holds a fixed number of items of the same data type under one name. Each item (element) is picked out by its index.
names = ["Aled", "Bryn", "Ceri", "Dewi"]
index: 0 1 2 3
OUTPUT names[2] // Ceri
names[0] = "Anwen" // changes the first element
- In these notes indexes start at 0, so an array of 4 elements has indexes 0 to 3. Some languages and exam papers start at 1; check the question.
- The elements are stored next to each other in memory, so any element can be reached directly from its index. This is random access and is very fast.
- An array is usually static: its size is fixed when it is declared.
Processing every element uses a loop:
total = 0
FOR i = 0 TO 3
total = total + marks[i]
NEXT i