An array stores multiple values of the same data type under one name. Each item has an index (usually starting at 0). Example: scores = [12, 8, 15]; scores[0] is 12.
One-dimensional (1D) arrays are lists; two-dimensional (2D) arrays are tables with rows and columns: grid[row][column].
Arrays have a fixed size in many languages; lists may grow.
Indexed array
Using arrays
Traversal visits elements using their valid indices. For total = 0 and scores = [12, 8, 15], an inclusive FOR loop from 0 to 2 adds all three elements to give 35.
Initialise an accumulator before adding values. For a maximum search, initialise from the first element of a non-empty array rather than assuming zero is a valid starting maximum.
Array traversal
Records
A record groups named fields about one entity, such as a student’s name, age and grade. Fields may have different types.
Collections of records may be held in files or database tables; not every record file by itself is a database system.
When to use
Use arrays for lists of the same type; records for related fields of different types.
Advantages
Arrays avoid many separate variables, make code shorter and loops possible.
Two-dimensional arrays
grid[row][column]
Rows and columns
Nested loops
Accessing a two-dimensional array
投影片
Sign up free to view the lesson slides
Step through every slide for this topic — plus flashcards and revision notes — with a free account.