Arrays
Arrays
- An array is an ordered collection of items of the same type, under one name, reached by an index.
- It's the workhorse for storing lists and tables.
- Loops let you process every element.
1-D arrays
DECLARE Names : ARRAY[1:5] OF STRING
Names[3] ← "Cara"
FOR i ← 1 TO 5
OUTPUT Names[i]
NEXT i
- An element is one item; the bounds are the lowest and highest valid indices.
- A
FORloop visits every element in turn.
Practice
An array stores:
An array is an ordered collection of same-type items accessed by index. (A record groups different types.)
2-D arrays
DECLARE Grid : ARRAY[1:3, 1:4] OF INTEGER
Grid[2, 3] ← 99 // row 2, column 3
- The first index is the row, the second the column; use nested loops to visit every cell.
- Use 1-D for a single sequence, 2-D for a grid (rows × columns).
Practice
In Grid[2, 3], which cell is accessed?
The first index is the row, the second the column — so row 2, column 3.
Practice
A 2-D array is the natural choice for:
Two natural dimensions (rows and columns) suit a 2-D array; a single sequence uses 1-D.
Common operations
- Linear search checks each element until found:
FOR i ← 1 TO n
IF A[i] = Target THEN OUTPUT "Found at ", i
NEXT i
- For a sum, count, max or min, set a running variable then sweep through (e.g.
Max ← A[1], then compare each element).
Practice
A linear search finds a value by:
A linear search examines elements one by one from the start until it finds the target (or reaches the end).
You've got it
Key idea
- an array holds many items of the same type, reached by an index, within its bounds
- 1-D = a list; 2-D = a table (
Grid[row, column]), visited with nested loops - a linear search checks each element in turn
- running totals/max/min: initialise a variable, then loop through