Arrays
One name holding many values, so a loop can work through them.
WATCH IT EXPLAINED
EXPLORE IT IN 3D
The array warehouse
A robot warehouse stores values the way an array does: one name on the shelf, a numbered bin for each element. Fill it, search it and sort it — and walk into the exam's traps on purpose.
One name, many values
An array keeps many values of one type under one name, and an index picks out each one.
Think of a week of temperatures in Ulaanbaatar. Seven separate variables are messy. One array can hold all seven.
- An array has a fixed number of elements (single values).
- Every element has the same data type.
- Each element is found by its index (its position number).
DECLARE Temps : ARRAY[1:7] OF INTEGER makes seven integers, Temps[1] to Temps[7].
Number of elements = upper bound − lower bound + 1. So ARRAY[0:7] would hold eight.
Remember:The first index can be 0 or 1, so always state the lower bound (the first index). This lesson uses 1.
Watch out:An index outside the bounds is an error.
DECLARE Temps : ARRAY[1:7] OF INTEGER Temps[3] ← -15 OUTPUT Temps[3]
Filling and reading an array with a loop
Use the loop counter as the index, and one loop visits every element of the array.
The index does not have to be a fixed number. It can be a variable. So one loop can visit every element: FOR Day ← 1 TO 7, and then Temps[Day].
The same loop shape does two jobs:
- Write values into the array:
INPUT Temps[Day] - Read them out again:
OUTPUT Temps[Day]
Watch out:Use the loop counter as the index, and make its range match the array's bounds. Temps is [1:7], so the loop goes from 1 to 7.
Processing a whole array
To find the smallest value, start with element 1 as the answer so far, then compare every other element with it.
The standard methods from topic 2.1.3, such as finding the minimum, work on an array in the same way. Here is how to find the coldest day:
- Take element 1 as the answer so far.
- Loop from element 2 to the end.
- Compare each element with the answer so far.
Remember:Starting with element 1 is always safe. The answer is then one of the real values.
Do you also need to say where the answer is, not only what it is? Keep its index in a second variable, ColdestDay. Change both variables together.
Two-dimensional arrays
A 2-D array is a table of rows and columns, so every element needs two indexes.
A two-dimensional array (2-D array) is a table of elements, in rows and columns. Think of a mark sheet with rows and columns of marks.
DECLARE Marks : ARRAY[1:3, 1:4] OF INTEGER has 3 × 4 = 12 elements.
Each element needs two indexes, one for each dimension. For example, Marks[2, 3].
Watch out:The usual convention is [row, column], but the guide does not fix it. The question will say which index is which. Read that before you answer.
DECLARE Marks : ARRAY[1:3, 1:4] OF INTEGER Marks[2, 1] ← 90 Marks[2, 2] ← 85 Marks[2, 3] ← 88 Marks[2, 4] ← 92 OUTPUT Marks[2, 3]
Nested loops over a 2-D array
Put one loop inside another: the outer loop picks a row, and the inner loop goes along it.
To visit every element of a 2-D array, put one loop inside another.
- The outer loop picks the row.
- The inner loop goes along that row.
- The inner loop runs completely for every pass of the outer one.
Do you want a total for each row? Set that total to 0 inside the outer loop, just before the inner loop.
Remember:This is the totalling rule: set a total to 0 just before the loop that adds to it.
Linear search
A linear search checks the elements one by one, from the first, until it finds the item or reaches the end.
A linear search checks each element in turn, starting from the first. It stops when it finds the item or reaches the end.
- Good: it works on data in any order.
- Bad: in the worst case it checks every element.
How to write it:
- Set
Found ← FALSEbefore the loop. - Use a
WHILEloop, so the search stops as soon as the item is found. - Output "not found" only after the loop.
The FOR version below checks every element, so it can count every match. Given Bat at positions 2 and 4, it prints both positions and then "2 found".
Watch out:Matching is exact: "nomin" is not "Nomin".
DECLARE Names : ARRAY[1:8] OF STRING DECLARE Index : INTEGER DECLARE Count : INTEGER DECLARE Target : STRING FOR Index ← 1 TO 8 INPUT Names[Index] NEXT Index INPUT Target Count ← 0 FOR Index ← 1 TO 8 IF Names[Index] = Target THEN OUTPUT Target, " found at position ", Index Count ← Count + 1 ENDIF NEXT Index OUTPUT Count, " found"
Swapping needs a third variable
To swap two values, first copy one into a third variable, or it is lost.
Imagine two full cups of juice. To swap them, you need a third, empty cup. Values are the same: you need a temporary store.
Watch out:A ← B then B ← A does not work. The first line copies B into A. A's old value is gone before it can be copied back.
The three-step swap:
Temp ← AA ← BB ← Temp
Every swap in a bubble sort uses exactly these three lines.
Bubble sort: one pass
One pass of a bubble sort compares each pair of neighbours and swaps them if they are in the wrong order.
A bubble sort compares neighbouring elements, List[Index] and List[Index + 1]. If they are the wrong way round, it swaps them.
One pass goes from the start of the list to the end. In ascending order (smallest first), one pass carries the largest value to the end.
Example:With 5 elements, a pass makes 4 comparisons. The index only goes up to 4, because element 4 is compared with element 5.
Watch out:Going up to 5 would read List[6], which does not exist.
A better bubble sort
Two changes make a bubble sort faster: stop when a pass makes no swaps, and make each pass one place shorter.
The simple version always makes n − 1 passes, each with n − 1 comparisons. Mark schemes give credit for two improvements:
- A flag (a TRUE or FALSE variable) called
Swapped. It is set toFALSEat the start of each pass, and toTRUEwhenever a swap happens. A pass with no swaps means the list is sorted, so the sort stops. - Shorter passes. Each pass stops one place earlier, because the end of the list is already sorted.
Remember:To sort in descending order, change > to <.
Pass ← 0 REPEAT Pass ← Pass + 1 Swapped ← FALSE FOR Index ← 1 TO Size - Pass IF List[Index] > List[Index + 1] THEN Temp ← List[Index] List[Index] ← List[Index + 1] List[Index + 1] ← Temp Swapped ← TRUE ENDIF NEXT Index UNTIL Swapped = FALSE OR Pass = Size - 1
Array traps in the exam
Most array mistakes are off by one, so check where every loop starts and stops.
A common array mistake is being off by one: a loop that runs one step too far, or stops one step short.
Before you hand in an array answer, go through this checklist:
- Does each loop's range match the array's bounds?
- Does a pairwise comparison stop one before the end? (
Size - 1, orSize - Pass) - Is the element count upper − lower + 1?
- Does every swap go through
Temp? - Should you output the index or the value?
- In a 2-D array, which index is the row? Read the question.
RUN THE PSEUDOCODE
Write the pseudocode your syllabus uses and press Run. Assignment is the arrow — type <- and it works the same as ←. Both syllabuses are accepted, so OUTPUT and PRINT both work; where a word differs from the one the exam prints, the runner says so.
Press Run to see what it doesTotal ← 0
FOR Count ← 1 TO N
Total ← Total + Count
NEXT Count
OUTPUT TotalSTARTN = 5
| Count | Total | OUTPUT |
|---|---|---|
One row per pass through the loop. Leave a cell blank if it does not change on that pass.
KEY TERMS
CHECK YOURSELF
1.An array is DECLARE A : ARRAY[1:10] OF INTEGER. How many values can it hold?
2.Why does swapping two array elements need a third variable?
3.DECLARE Marks : ARRAY[1:3, 1:4] OF INTEGER. How many elements does Marks have?
4.List is ARRAY[1:5]. One pass of a bubble sort compares List[Index] with List[Index + 1]. What is the last value Index should take?
5.A linear search starts with Found ← FALSE. Where should it output "not found"?
6.Why does an efficient bubble sort use a flag such as Swapped?