Choosing a data type
The characters 12 can be a number to add to, or just two symbols on a label, and a program treats the two very differently. A data type fixes what values a variable can hold and what can be done with them. Choose the type from how the value is used, not from how it looks.
How to choose a type
Ask what the program will do with the value, and the type follows from the answer.
| Value or use | Type | Why |
|---|---|---|
"03/09/2024" in quotes | STRING | the quotes make it text, not a date |
03/09/2024, no quotes | DATE | an unquoted date value, or a date used in calculations |
"0712 345678", a phone number | STRING | keeps the leading 0; never used in arithmetic |
Total / Count | REAL | / always gives a REAL, even for two integers |
LEFT(Code, 1) | CHAR | exactly one character (a STRING also works) |
Mark >= 50 | BOOLEAN | a comparison is either TRUE or FALSE |
Index, a position in an array | INTEGER | an index is always a whole number |
DECLARE Num : INTEGER DECLARE Text : STRING Num ← 12 Text ← "12" OUTPUT Num + 3 // 15 OUTPUT Text & "3" // 123 OUTPUT STR_TO_NUM(Text) + 3 // 15 OUTPUT 7 / 2 // 3.5 OUTPUT 7 DIV 2 // 3
Writing a literal of each type
- INTEGER
42,-3· REAL with a digit on each side of the point:4.0,0.5 - CHAR in single quotes:
'Y'· STRING in double quotes:"Ali";""is the empty string - BOOLEAN
TRUE,FALSE· DATE normallydd/mm/yyyy, so state the format you use
1 A runner’s number of laps, used in a total. Which type?
2 The result of Distance / Laps. Which type?
3 A membership number "00731" that must keep its leading zeros. Which type?
4 Whether a runner has paid. Which type?
- 1INTEGER: a whole number used in arithmetic
- 2REAL:
/always gives a REAL - 3STRING: a number type would drop the zeros, and it is never used in arithmetic
- 4BOOLEAN
CHAR, not CHARACTER; INTEGER or REAL, not just “number”. Fit the type to the use: a date in quotes or a phone number is a STRING, a value made by / is a REAL, a count or an index is an INTEGER.Records: one identifier, many types
A runner has an ID, a name, an age, a best time and more: different kinds of data that all belong to one person. A record type, defined by the programmer, groups a set of related data items, which can be of different data types, under one identifier. Each item in the record is a field.
Read the code in three parts: TYPE sets out the fields, DECLARE makes one variable, and the dot reaches one field. The boxes show what Runner holds once every line has run.
TYPE RunnerRecord DECLARE RunnerID : STRING DECLARE Name : STRING DECLARE Age : INTEGER DECLARE BestTime : REAL DECLARE Category : CHAR DECLARE Paid : BOOLEAN DECLARE Joined : DATE ENDTYPE DECLARE Runner : RunnerRecord Runner.RunnerID ← "R0417" Runner.Name ← "Mei Lin" Runner.Age ← 16 Runner.BestTime ← 21.75 Runner.Category ← 'J' Runner.Paid ← FALSE Runner.Joined ← SETDATE(3, 9, 2024) OUTPUT Runner.Name, " ", Runner.BestTime
Why use a record?
- All the data about one item is held under a single identifier.
- The fields can be of different data types.
- The whole record can be copied in one statement:
Copy ← Runner.
Do not confuse
TYPE RunnerRecord defines a new data type: a layout that holds no data. DECLARE Runner : RunnerRecord creates a variable with that layout. Write Runner.Age, never RunnerRecord.Age.
Read and write any field
A field is used like any variable: INPUT Runner.Age, Runner.Age ← Runner.Age + 1. A DATE field is set with SETDATE(day, month, year).
Match each field type to its example value
| Example | Type | Example | Type |
|---|---|---|---|
"L2207" | STRING | 2 | INTEGER |
0.75 | REAL | 'R' | CHAR |
FALSE | BOOLEAN | 14/10/2026 | DATE |
1 Add a field Laps that holds a whole number. Write its line inside TYPE RunnerRecord.
2 Write one statement that adds 1 to the age stored in Runner.
3 What is wrong with RunnerRecord.Name ← "Ada"?
- 1
DECLARE Laps : INTEGER - 2
Runner.Age ← Runner.Age + 1 - 3
RunnerRecordis the type, which holds no data; use the variable:Runner.Name ← "Ada"
TYPE RunnerRecord … ENDTYPE and one DECLARE Field : TYPE line per field; match each field type to its values and use. The purpose: data of different types about one item, held under one identifier.Arrays of records
A squad of 50 runners needs 50 records, and 50 separate variables could never be processed in a loop. To store many records, declare a 1D array whose element type is the record type. The index selects the record; the dot selects the field.
Each index selects one runner's whole record. To read Squad[4].BestTime, find index 4, then its BestTime field.
Squad[1:50]: each index selects the same record in both panels.
| Index | RunnerID | Name |
|---|---|---|
| 1 | R0417 | Mei Lin |
| 2 | R0388 | Tomas Ruiz |
| 3 | "" | unused |
| 4 | R0452 | Ada Okoro |
| 5 | R0390 | Sam Patel |
| 6–50 | "" | unused |
| Index | Age | Paid | BestTime |
|---|---|---|---|
| 1 | 16 | TRUE | 21.75 |
| 2 | 17 | TRUE | 19.5 |
| 3 | — | — | — |
| 4 | 15 | FALSE | 23.25 |
| 5 | 16 | TRUE | 20.5 |
| 6–50 | — | — | — |
Squad[4].BestTime = 23.25: index 4 selects Ada's record; the dot selects BestTime.DECLARE Squad : ARRAY[1:50] OF RunnerRecord DECLARE Index, Count : INTEGER DECLARE Total : REAL Count ← 0 Total ← 0.0 FOR Index ← 1 TO 50 IF Squad[Index].RunnerID <> "" THEN Count ← Count + 1 Total ← Total + Squad[Index].BestTime ENDIF NEXT Index IF Count > 0 THEN OUTPUT "Mean best time: ", Total / Count ENDIF
Mean best time: 21.25
Mark unused elements
Store an impossible value in a key field, e.g. an empty string ID or an age of 0 if it is outside the allowed age range. Initialise the marker in every unused record so loops can skip it.
Benefits of an array of records
- Data of different types for every runner, held under one identifier.
- A loop with an index processes every record;
Squad[4]reaches one record directly. - Moving a whole record keeps its runner's fields together when records are copied or sorted.
The alternative: parallel 1D arrays
| Index | Name | BestTime |
|---|---|---|
| 1 | Mei Lin | 21.75 |
| 2 | Tomas Ruiz | 19.5 |
| 3 | "" | — |
| 4 | Ada Okoro | 23.25 |
The same index links the name and time in the two parallel arrays.
1 What does Squad[2].Name hold?
2 Which indexes does the loop add to Total, and what is Count at the end?
3 Element 5 is marked unused as well. What does the program output now?
- 1"Tomas Ruiz"
- 21, 2, 4, 5; Count = 4
- 3Mean best time: 21.5: (21.75 + 19.5 + 23.25) ÷ 3
DECLARE Squad : ARRAY[1:50] OF RunnerRecord. Benefits that earn marks: different data types under one identifier, records processed in a loop using an index, simpler code.Arrays: index, bounds and dimensions
Thirty names in thirty separate variables would need thirty nearly identical lines for every job. An array is a fixed-size group of elements of the same data type under one identifier. Each element is selected by an index, which must lie between the lower bound and the upper bound.
Each box is one element and the number under it is its index. A 1D array is one row of boxes; a 2D array is a grid, so it needs two indexes, row first.
Declaring an array and counting its elements
A declaration tells you exactly how big an array is, once you can read its bounds.
DECLARE Names : ARRAY[1:30] OF STRINGDECLARE Hits : ARRAY[0:9] OF INTEGERDECLARE Seat : ARRAY[1:3, 1:5] OF CHARDECLARE Usage : ARRAY[0:23, 1:7] OF REALThe terms
- Index (subscript): the number that selects one element.
- Lower bound and upper bound: the smallest and largest index of a dimension.
- Dimension: 1D needs one index; 2D needs two, e.g. row and column.
Why an array, not separate variables?
- One identifier for many values: fewer identifiers.
- Values are processed in a loop, using the loop counter as the index.
- The program is easier to write, test and amend, e.g. change the upper bound for more values.
1 DECLARE Laps : ARRAY[0:11] OF INTEGER. How many elements does it have?
2 DECLARE Board : ARRAY[1:4, 0:9] OF CHAR. How many elements does it have?
3 Declare an array for 20 names, indexed from 1.
- 112: 11 − 0 + 1
- 240: 4 rows × 10 columns
- 3
DECLARE Names : ARRAY[1:20] OF STRING
DECLARE Seat : ARRAY[1:3, 1:5] OF CHAR. Give both bounds for every dimension, joined by a colon, inside square brackets, a comma between dimensions, then OF and the type. Round brackets are not accepted.Choosing and processing 1D arrays
Before writing any code, look at the shape of the data: one list of one type is a 1D array. A loop whose counter is the index can then process every element.
Select a suitable structure
One list, a grid, or several types for each item: the shape of the data decides the structure.
| Data to store | Structure | Reason |
|---|---|---|
| the names of 30 students | ARRAY[1:30] OF STRING | one list of one type: 1D |
| rainfall for 52 weeks × 7 days | ARRAY[1:52, 1:7] OF REAL | two indexes, week and day: 2D |
| 20 × 30 seats, booked or not | ARRAY[1:20, 1:30] OF BOOLEAN | two indexes, row and seat: 2D |
| a name and a score per student | array of records, or two 1D arrays | two types, so not one 2D array |
Process the elements with a loop
Rain[1:7] holds 0.0, 4.5, 12.0, 0.0, 3.5, 0.0, 7.0 mm. Find the total, number of wet days and index of the wettest day.
1DECLARE Day, WetDays, Wettest : INTEGER 2DECLARE Total : REAL 3Total ← 0.0 4WetDays ← 0 5Wettest ← 1 6FOR Day ← 1 TO 7 7Total ← Total + Rain[Day] 8IF Rain[Day] > 0.0 THEN 9WetDays ← WetDays + 1 10ENDIF 11IF Rain[Day] > Rain[Wettest] THEN 12Wettest ← Day 13ENDIF 14NEXT Day 15OUTPUT "Total: ", Total 16OUTPUT "Wet days: ", WetDays 17OUTPUT "Wettest day: ", Wettest
Total: 27.0 Wet days: 4 Wettest day: 3
DECLARE Day : INTEGER FOR Day ← 1 TO 7 Rain[Day] ← 0.0 NEXT Day
Trace the loop one day at a time
A trace shows what the loop does with each day’s value. Write one row per pass, and a value only where a line writes it.
| Line | Statement that runs | Day | Total | WetDays | Wettest | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 6 | FOR Day ← 1 TO 7 | 3 | Day 3 | the third time round the loop | |||
| the third time round the loop | |||||||
| 7 | Total ← Total + Rain[Day] | 16.5 | Total 16.5 | 4.5 + 12.0 = 16.5 | |||
| 4.5 + 12.0 = 16.5 | |||||||
| 8 | IF Rain[Day] > 0.0 THEN | test 12.0 > 0.0 is true | |||||
| test 12.0 > 0.0 is true | |||||||
| 9 | WetDays ← WetDays + 1 | 2 | WetDays 2 | one more wet day | |||
| one more wet day | |||||||
| 11 | IF Rain[Day] > Rain[Wettest] THEN | test 12.0 > Rain[2], which is 4.5: true | |||||
| test 12.0 > Rain[2], which is 4.5: true | |||||||
| 12 | Wettest ← Day | 3 | Wettest 3 | remember the index, not the value | |||
| remember the index, not the value | |||||||
Day | Rain[Day] | Total | WetDays | Wettest | What happens | |
|---|---|---|---|---|---|---|
| start | 0.0 | 0 | 1 | lines 3 to 5, before the loop | ||
| lines 3 to 5, before the loop | ||||||
| pass 1 | 1 | 0.0 | 0.0 | 0.0: not a wet day | ||
| 0.0: not a wet day | ||||||
| pass 2 | 2 | 4.5 | 4.5 | 1 | 2 | 4.5 > 0.0: a wet day; 4.5 > Rain[1]: new wettest |
| 4.5 > 0.0: a wet day; 4.5 > Rain[1]: new wettest | ||||||
| pass 3 | 3 | 12.0 | 16.5 | 2 | 3 | 12.0 > 0.0: a wet day; 12.0 > Rain[2]: new wettest |
| 12.0 > 0.0: a wet day; 12.0 > Rain[2]: new wettest | ||||||
| pass 4 | 4 | 0.0 | 16.5 | 0.0: not a wet day | ||
| 0.0: not a wet day | ||||||
| pass 5 | 5 | 3.5 | 20.0 | 3 | 3.5 > 0.0: a wet day | |
| 3.5 > 0.0: a wet day | ||||||
| pass 6 | 6 | 0.0 | 20.0 | 0.0: not a wet day | ||
| 0.0: not a wet day | ||||||
| pass 7 | 7 | 7.0 | 27.0 | 4 | 7.0 > 0.0: a wet day | |
| 7.0 > 0.0: a wet day | ||||||
Do not confuse
- Do not assign a range in one statement, such as
Rain[1 TO 7] ← 0.0: assign each element inside a loop. - Copying a whole array,
Copy ← Rain, is allowed when both have the same size and type. - Keep the loop inside the bounds:
1 TO 7forARRAY[1:7],0 TO 6forARRAY[0:6].
1 Another week holds 2.0, 0.0, 6.5, 9.0, 0.0, 9.0, 1.5. What is the total?
2 How many wet days are there?
3 Days 4 and 6 both hold 9.0. Which index does Wettest end on, and why?
- 128.0
- 25
- 34: the test is
>, so the equal value on day 6 does not replace it
Tracing strings inside an array
Strings stored in an array have two kinds of position, and mixing them up is the quickest way to lose a trace. An array index chooses a string; a character position chooses part of that string.
1// Labels initially holds "Mei Lin", "Tomas Ruiz", "Ada Okoro" 2// Limits holds 3, 5, 4 3DECLARE Index, Limit : INTEGER 4DECLARE C : CHAR 5DECLARE Modes, Result : STRING 6Modes ← "UL?" 7Result ← "hold" 8FOR Index ← 1 TO 3 9C ← MID(Modes, Index, 1) 10Limit ← Limits[Index] 11CASE OF C 12'U' : Result ← TO_UPPER(Labels[Index]) 13'L' : Result ← TO_LOWER(Labels[Index]) 14'P' : Result ← "#" & Labels[Index] 15ENDCASE 16Labels[Index] ← LEFT(Result, Limit) 17NEXT Index
Snapshots after each assignment to Labels[Index]
Each pass makes two decisions: which branch runs, and what is stored in Labels[Index]. Trace them in that order.
| Line | Statement that runs | Index | C | Limit | Labels[3] | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 8 | FOR Index ← 1 TO 3 | 3 | Index 3 | the last pass | |||
| the last pass | |||||||
| 9 | C ← MID(Modes, Index, 1) | '?' | C '?' | character 3 of "UL?" | |||
| character 3 of "UL?" | |||||||
| 10 | Limit ← Limits[Index] | 4 | Limit 4 | Limits[3] | |||
| Limits[3] | |||||||
| 11 | CASE OF C | test '?' is not 'U', 'L' or 'P': no branch runs | |||||
| test '?' is not 'U', 'L' or 'P': no branch runs | |||||||
| 16 | Labels[Index] ← LEFT(Result, Limit) | "toma" | Labels[3] "toma" | LEFT("tomas ruiz", 4): Result still holds the Index 2 value | |||
| LEFT("tomas ruiz", 4): Result still holds the Index 2 value | |||||||
C | Limit | Result | Labels[1] | Labels[2] | Labels[3] | What happens | |
|---|---|---|---|---|---|---|---|
| start | "hold" | "Mei Lin" | "Tomas Ruiz" | "Ada Okoro" | lines 6 and 7; Labels as given | ||
| lines 6 and 7; Labels as given | |||||||
| Index 1 | 'U' | 3 | "MEI LIN" | "MEI" | 'U' runs line 12; LEFT keeps 3 characters | ||
| 'U' runs line 12; LEFT keeps 3 characters | |||||||
| Index 2 | 'L' | 5 | "tomas ruiz" | "tomas" | 'L' runs line 13; LEFT keeps 5 characters | ||
| 'L' runs line 13; LEFT keeps 5 characters | |||||||
| Index 3 | '?' | 4 | "toma" | '?' matches no branch: Result keeps its value | |||
| '?' matches no branch: Result keeps its value | |||||||
C | Limit | Result | Labels[Index] | What happens | |
|---|---|---|---|---|---|
| start | "hold" | lines 6 and 7; Labels as given | |||
| lines 6 and 7; Labels as given | |||||
| Index 1 | 'U' | 3 | "MEI LIN" | "MEI" | 'U' runs line 12; LEFT keeps 3 characters |
| 'U' runs line 12; LEFT keeps 3 characters | |||||
| Index 2 | 'L' | 5 | "tomas ruiz" | "tomas" | 'L' runs line 13; LEFT keeps 5 characters |
| 'L' runs line 13; LEFT keeps 5 characters | |||||
| Index 3 | '?' | 4 | "toma" | '?' matches no branch: Result keeps its value | |
| '?' matches no branch: Result keeps its value | |||||
The same snapshots, character by character
Each row is one element of Labels; the numbers above are character positions. Blue: the element changed in that pass.
| Snapshot | C | Limit | Result | Labels[1] | Labels[2] | Labels[3] |
|---|---|---|---|---|---|---|
| Initial state | — | — | "hold" | "Mei Lin" | "Tomas Ruiz" | "Ada Okoro" |
| After Index = 1 | U | 3 | "MEI LIN" | "MEI" | "Tomas Ruiz" | "Ada Okoro" |
| After Index = 2 | L | 5 | "tomas ruiz" | "MEI" | "tomas" | "Ada Okoro" |
| After Index = 3 | ? | 4 | "tomas ruiz" | "MEI" | "tomas" | "toma" |
Index versus character position
At Index 2, MID(Modes, 2, 1) is 'L'. Labels[2] is the whole string "Tomas Ruiz"; LEFT(Result, 5) keeps its first five characters.
No matching CASE branch
'?' matches none of U, L or P. There is no OTHERWISE, so Result stays "tomas ruiz". The assignment after ENDCASE still runs, setting Labels[3] to "toma".
1 Modes is changed to "PLU". Labels holds Kai Moss, Lu Chen, Ines Roy and Limits holds 2, 6, 3. What is stored in Labels[1]?
2 What is stored in Labels[2]?
3 What is stored in Labels[3]?
4 What does Result hold when the loop ends?
- 1
"#K": "#" & "Kai Moss", then the first 2 characters - 2
"lu che" - 3
"INE" - 4
"INES ROY": Result keeps the whole string; only the stored copy is cut
Tracing an array: copying the values that pass a test
Picking values out of a list leaves gaps unless something keeps track of where the next one goes. A value is copied only when it passes the test. Count is the next free position in Picked, so the copies fill it from index 1 with no gaps.
Nums[1:6] initially holds 31, 12, 47, 8, 26, 39. Copy a value only if it is less than 40.
1DECLARE Picked : ARRAY[1:6] OF INTEGER 2DECLARE J, Count : INTEGER 3Count ← 0 4FOR J ← 1 TO 6 5IF Nums[J] < 40 THEN 6Count ← Count + 1 7Picked[Count] ← Nums[J] 8ENDIF 9NEXT J
Snapshots after each IF
J moves on every pass, but Count moves only when a value is copied. For each J, trace the test first, then Count and the array write.
| Line | Statement that runs | J | Count | Picked[Count] | Writes | What happens |
|---|---|---|---|---|---|---|
| 4 | FOR J ← 1 TO 6 | 4 | J 4 | the fourth Nums element | ||
| the fourth Nums element | ||||||
| 5 | IF Nums[J] < 40 THEN | test Nums[4] is 8: 8 < 40 is true | ||||
| test Nums[4] is 8: 8 < 40 is true | ||||||
| 6 | Count ← Count + 1 | 3 | Count 3 | the next free position in Picked | ||
| the next free position in Picked | ||||||
| 7 | Picked[Count] ← Nums[J] | 8 | Picked[Count] 8 | so 8 goes into Picked[3], not Picked[4] | ||
| so 8 goes into Picked[3], not Picked[4] | ||||||
J | Nums[J] | Count | Picked[Count] | What happens | |
|---|---|---|---|---|---|
| start | 0 | line 3: no value copied yet | |||
| line 3: no value copied yet | |||||
| J 1 | 1 | 31 | 1 | 31 | 31 < 40: Picked[1] ← 31 |
| 31 < 40: Picked[1] ← 31 | |||||
| J 2 | 2 | 12 | 2 | 12 | 12 < 40: Picked[2] ← 12 |
| 12 < 40: Picked[2] ← 12 | |||||
| J 3 | 3 | 47 | 47 < 40 is false: nothing is written | ||
| 47 < 40 is false: nothing is written | |||||
| J 4 | 4 | 8 | 3 | 8 | 8 < 40: Picked[3] ← 8 |
| 8 < 40: Picked[3] ← 8 | |||||
| J 5 | 5 | 26 | 4 | 26 | 26 < 40: Picked[4] ← 26 |
| 26 < 40: Picked[4] ← 26 | |||||
| J 6 | 6 | 39 | 5 | 39 | 39 < 40: Picked[5] ← 39 |
| 39 < 40: Picked[5] ← 39 | |||||
1DECLARE Picked : ARRAY[1:6] OF INTEGER 2DECLARE J, Count : INTEGER 3Count ← 0 4FOR J ← 1 TO 6 5IF Nums[J] < 40 THEN 6Count ← Count + 1 7Picked[Count] ← Nums[J] 8ENDIF 9NEXT J
Snapshots after each IF
| J | Nums[J] | Count after IF | Array assignment |
|---|---|---|---|
| 1 | 31 | 1 | Picked[1] = 31 |
| 2 | 12 | 2 | Picked[2] = 12 |
| 3 | 47 | 2 | — |
| 4 | 8 | 3 | Picked[3] = 8 |
| 5 | 26 | 4 | Picked[4] = 26 |
| 6 | 39 | 5 | Picked[5] = 39 |
Completed state: Count = 5
| Index | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| Nums | 31 | 12 | 47 | 8 | 26 | 39 |
| Picked | 31 | 12 | 8 | 26 | 39 | unused |
An index is not the stored value
J visits all six Nums elements, but Count increases only five times. At J = 3, Nums[3] is 47: the test fails, Count stays 2 and no Picked element is assigned. The next value, 8, goes into Picked[3].
1 Nums holds 45, 12, 39, 40, 7, 52. Which values are copied into Picked, in order?
2 What is Count at the end?
3 At which J is Picked[2] written?
- 112, 39, 7: 45, 40, 52 fail the test (40 < 40 is false)
- 23
- 3J = 3
Tracing an array: searching it backwards
Programs often run in stages, and each stage starts from whatever the last one left behind. Stage 2 picks up Picked, the values under 40, with Count = 5; it walks Pos back to the last even value and changes neither Nums nor Picked.
Starting state: Count = 5
| Index | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| Nums | 31 | 12 | 47 | 8 | 26 | 39 |
| Picked | 31 | 12 | 8 | 26 | 39 | unused |
1DECLARE Pos : INTEGER 2DECLARE Found : BOOLEAN 3Pos ← Count 4Found ← FALSE 5REPEAT 6IF Picked[Pos] MOD 2 = 0 THEN 7Found ← TRUE 8ELSE 9Pos ← Pos - 1 10ENDIF 11UNTIL Found OR Pos = 0 12IF Found THEN 13OUTPUT Picked[Pos] 14ELSE 15OUTPUT "No even value" 16ENDIF
Follow the test, then the update
At Pos 5, 39 is odd, so Pos falls to 4. At Pos 4, 26 is even, so Found becomes TRUE and the loop ends. Output: 26. Picked stays 31, 12, 8, 26, 39 throughout.
Snapshots at each test
A REPEAT loop checks its condition at the end, so each pass has three steps: the test, the update, then the UNTIL condition.
| Line | Statement that runs | Pos | Found | Writes | What happens |
|---|---|---|---|---|---|
| 6 | IF Picked[Pos] MOD 2 = 0 THEN | test Picked[5] is 39; 39 MOD 2 = 1, so the test is false | |||
| test Picked[5] is 39; 39 MOD 2 = 1, so the test is false | |||||
| 9 | Pos ← Pos - 1 | 4 | Pos 4 | the ELSE branch moves back one element | |
| the ELSE branch moves back one element | |||||
| 11 | UNTIL Found OR Pos = 0 | test Found is FALSE and Pos is not 0: false, so repeat | |||
| test Found is FALSE and Pos is not 0: false, so repeat | |||||
Pos | Picked[Pos] | Found | What happens | |
|---|---|---|---|---|
| start | 5 | FALSE | lines 3 and 4: start at the last used element | |
| lines 3 and 4: start at the last used element | ||||
| Pos 5 | 4 | 39 | 39 MOD 2 = 1: odd, so Pos ← 4 | |
| 39 MOD 2 = 1: odd, so Pos ← 4 | ||||
| Pos 4 | 26 | TRUE | 26 MOD 2 = 0: even, so Found ← TRUE and the UNTIL test ends the loop | |
| 26 MOD 2 = 0: even, so Found ← TRUE and the UNTIL test ends the loop | ||||
1DECLARE Pos : INTEGER 2DECLARE Found : BOOLEAN 3Pos ← Count 4Found ← FALSE 5REPEAT 6IF Picked[Pos] MOD 2 = 0 THEN 7Found ← TRUE 8ELSE 9Pos ← Pos - 1 10ENDIF 11UNTIL Found OR Pos = 0 12IF Found THEN 13OUTPUT Picked[Pos] 14ELSE 15OUTPUT "No even value" 16ENDIF
Snapshots at each test
| Pos at test | Picked[Pos] | Found after test |
|---|---|---|
| 5 | 39 | FALSE |
| 4 | 26 | TRUE |
Follow the test, then the update
At Pos 5, 39 is odd, so Pos falls to 4. At Pos 4, 26 is even, so Found becomes TRUE and the loop ends. Output: 26. Picked stays 31, 12, 8, 26, 39 throughout.
1 Stage 1 left Count = 5 and Picked[1:5] = 15, 9, 22, 7, 3. What is output?
2 What is Pos when the loop ends?
3 Count = 3 and Picked[1:3] = 5, 9, 3. What is output, and what is Pos?
- 122
- 23: 3 and 7 are odd, then 22 is even
- 3"No even value"; Pos is 0, so the UNTIL test ends the loop
Processing 2D arrays
Sales for three shops over four quarters form a grid, not a list. A 2D array stores a table: the first index selects the row, the second the column. Nested loops visit every element: the outer loop takes each row, the inner loop each column of it.
1DECLARE Shop, Qtr, Total : INTEGER 2FOR Shop ← 1 TO 3 3Total ← 0 4FOR Qtr ← 1 TO 4 5Total ← Total + Sales[Shop, Qtr] 6NEXT Qtr 7OUTPUT "Shop ", Shop, ": ", Total 8NEXT Shop
Shop 1: 56 Shop 2: 43 Shop 3: 54
DECLARE Shop, Qtr, Total : INTEGER FOR Qtr ← 1 TO 4 Total ← 0 FOR Shop ← 1 TO 3 Total ← Total + Sales[Shop, Qtr] NEXT Shop OUTPUT "Qtr ", Qtr, ": ", Total NEXT Qtr
Qtr 1: 37 Qtr 2: 32 Qtr 3: 36 Qtr 4: 48
Trace the nested loops
The inner loop does all the adding for one shop before the outer loop moves on. Trace it for one row, then give one row of the trace per shop.
| Line | Statement that runs | Shop | Qtr | Total | Output | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 2 | FOR Shop ← 1 TO 3 | 2 | Shop 2 | the second row | |||
| the second row | |||||||
| 3 | Total ← 0 | 0 | Total 0 | a fresh total for this row | |||
| a fresh total for this row | |||||||
| 4 | FOR Qtr ← 1 TO 4 | 1 | Qtr 1 | column 1 of row 2 | |||
| column 1 of row 2 | |||||||
| 5 | Total ← Total + Sales[Shop, Qtr] | 8 | Total 8 | + Sales[2, 1], which is 8 | |||
| + Sales[2, 1], which is 8 | |||||||
| 4 | FOR Qtr ← 1 TO 4 | 2 | Qtr 2 | column 2 of row 2 | |||
| column 2 of row 2 | |||||||
| 5 | Total ← Total + Sales[Shop, Qtr] | 19 | Total 19 | + Sales[2, 2], which is 11 | |||
| + Sales[2, 2], which is 11 | |||||||
| 4 | FOR Qtr ← 1 TO 4 | 3 | Qtr 3 | column 3 of row 2 | |||
| column 3 of row 2 | |||||||
| 5 | Total ← Total + Sales[Shop, Qtr] | 33 | Total 33 | + Sales[2, 3], which is 14 | |||
| + Sales[2, 3], which is 14 | |||||||
| 4 | FOR Qtr ← 1 TO 4 | 4 | Qtr 4 | column 4 of row 2 | |||
| column 4 of row 2 | |||||||
| 5 | Total ← Total + Sales[Shop, Qtr] | 43 | Total 43 | + Sales[2, 4], which is 10 | |||
| + Sales[2, 4], which is 10 | |||||||
| 7 | OUTPUT "Shop ", Shop, ": ", Total | Shop 2: 43 | Output Shop 2: 43 | after the inner loop ends | |||
| after the inner loop ends | |||||||
Shop | Sales[Shop, Qtr], Qtr 1 to 4 | Total after each | Output | What happens | |
|---|---|---|---|---|---|
| Shop 1 | 1 | 12, 15, 9, 20 | 12 → 27 → 36 → 56 | Shop 1: 56 | Total reset to 0, then 4 additions; output after NEXT Qtr |
| Total reset to 0, then 4 additions; output after NEXT Qtr | |||||
| Shop 2 | 2 | 8, 11, 14, 10 | 8 → 19 → 33 → 43 | Shop 2: 43 | Total reset to 0, then 4 additions; output after NEXT Qtr |
| Total reset to 0, then 4 additions; output after NEXT Qtr | |||||
| Shop 3 | 3 | 17, 6, 13, 18 | 17 → 23 → 36 → 54 | Shop 3: 54 | Total reset to 0, then 4 additions; output after NEXT Qtr |
| Total reset to 0, then 4 additions; output after NEXT Qtr | |||||
Reset the total in the right place
Where Total ← 0 sits decides whether each total starts again from 0. Say what is output when it moves.
Where Total ← 0 is placed | Output for shops 1, 2, 3 |
|---|---|
| inside the outer loop, before the inner loop | 56, 43, 54 ✓ correct |
| before both loops (only once) | 56, 99, 153 running totals |
| inside the inner loop, before the addition | 20, 10, 18 only the last quarter |
1 What is Sales[3, 1]?
2 In the column-total program, which loop is the outer loop?
3 Total ← 0 is moved before both loops in the column-total program. What is output for Qtr 2?
- 117: row 3, column 1
- 2the
Qtrloop: one column at a time - 3Qtr 2: 69: the Qtr 1 total, 37, is carried on and 32 is added
Sales[Shop, Qtr]. A loop over a dimension must run from its lower to its upper bound, such as 0 TO 2 for floors declared [0:2, 1:15].Reports from selected array elements
A manager reading a report wants to know that the best result was in quarter 4, not only that it was 20. In the same Sales grid, a high quarter has sales of at least 15, and the output gives the quarter's index, not just its stored value.
A manager reading a report wants to know that the best result was in quarter 4, not only that it was 20. In the same Sales table, a high quarter has sales of at least 15, and the output gives the quarter's index, not just its stored value. The single-row input is a valid shop number, 1–3.
Two programs read this grid: the first for one shop typed in (a valid number, 1 to 3), the second for every shop in turn. Watch where each header and count is output.
DECLARE Shop, Qtr, Count : INTEGER INPUT Shop Count ← 0 FOR Qtr ← 1 TO 4 IF Sales[Shop, Qtr] >= 15 THEN OUTPUT "Quarter ", Qtr Count ← Count + 1 ENDIF NEXT Qtr OUTPUT Count, " high quarters"
Quarter 2 Quarter 4 2 high quarters
DECLARE Shop, Qtr, Count : INTEGER Count ← 0 FOR Shop ← 1 TO 3 OUTPUT "Shop ", Shop FOR Qtr ← 1 TO 4 IF Sales[Shop, Qtr] >= 15 THEN OUTPUT "Quarter ", Qtr Count ← Count + 1 ENDIF NEXT Qtr NEXT Shop OUTPUT Count, " high quarters overall"
Shop 1 Quarter 2 Quarter 4 Shop 2 Shop 3 Quarter 1 Quarter 4 4 high quarters overall
1 The single-row program is run with Shop = 3. What is output?
2 In the every-row program, >= 15 is changed to >= 18. What is the last line of output?
3 Why is “Shop 2” output even though shop 2 has no high quarter?
- 1Quarter 1; Quarter 4; 2 high quarters
- 22 high quarters overall: only 20 and 18 reach 18
- 3the header is output inside the outer loop but outside the IF, so it runs once for every shop
Linear search
To find one code in an unsorted list there is no shortcut: start at the top and keep looking. A linear search checks each element in turn, starting with the first, until the item is found or every element has been checked. The data does not need to be sorted.
1DECLARE Index, FoundAt : INTEGER 2DECLARE Target : STRING 3INPUT Target 4FoundAt ← -1 5Index ← 1 6WHILE FoundAt = -1 AND Index <= 8 7IF Codes[Index] = Target THEN 8FoundAt ← Index 9ENDIF 10Index ← Index + 1 11ENDWHILE 12IF FoundAt = -1 THEN 13OUTPUT Target, " not found" 14ELSE 15OUTPUT Target, " found at ", FoundAt 16ENDIF
T05 found at 5
Why −1 and a conditional loop?
- −1 can never be a valid index, so it clearly means “not found”.
- The
WHILEsearch ends after the first match. With target B07, an unguardedFORloop reaches both matches: a match at 6 overwrites the index 2. GuardFoundAtagainst further updates, or stop at the first match.
Trace the search for T05
The loop can stop for two reasons: the code is found, or the list runs out. Each pass has three parts: the WHILE test, the comparison, then the updates.
| Line | Statement that runs | Index | FoundAt | Writes | What happens |
|---|---|---|---|---|---|
| 6 | WHILE FoundAt = -1 AND Index <= 8 | test FoundAt is −1 and Index 5 <= 8: true, so enter the loop | |||
| test FoundAt is −1 and Index 5 <= 8: true, so enter the loop | |||||
| 7 | IF Codes[Index] = Target THEN | test Codes[5] is "T05": true | |||
| test Codes[5] is "T05": true | |||||
| 8 | FoundAt ← Index | 5 | FoundAt 5 | remember where it was found | |
| remember where it was found | |||||
| 10 | Index ← Index + 1 | 6 | Index 6 | moved on, but the loop will not use it | |
| moved on, but the loop will not use it | |||||
Index | Codes[Index] | FoundAt | What happens | |
|---|---|---|---|---|
| start | −1 | lines 4 and 5 | ||
| lines 4 and 5 | ||||
| pass 1 | 1 | "K12" | "K12" ≠ "T05": Index ← 2 | |
| "K12" ≠ "T05": Index ← 2 | ||||
| pass 2 | 2 | "B07" | "B07" ≠ "T05": Index ← 3 | |
| "B07" ≠ "T05": Index ← 3 | ||||
| pass 3 | 3 | "M33" | "M33" ≠ "T05": Index ← 4 | |
| "M33" ≠ "T05": Index ← 4 | ||||
| pass 4 | 4 | "A19" | "A19" ≠ "T05": Index ← 5 | |
| "A19" ≠ "T05": Index ← 5 | ||||
| pass 5 | 5 | "T05" | 5 | "T05" = "T05": FoundAt ← 5; the WHILE test now fails |
| "T05" = "T05": FoundAt ← 5; the WHILE test now fails | ||||
1DECLARE Index, FoundAt : INTEGER 2DECLARE Target : STRING 3INPUT Target 4FoundAt ← -1 5Index ← 1 6WHILE FoundAt = -1 AND Index <= 8 7IF Codes[Index] = Target THEN 8FoundAt ← Index 9ENDIF 10Index ← Index + 1 11ENDWHILE 12IF FoundAt = -1 THEN 13OUTPUT Target, " not found" 14ELSE 15OUTPUT Target, " found at ", FoundAt 16ENDIF
Trace: Target = "T05"
Index | Codes[Index] | Match? | FoundAt |
|---|---|---|---|
| 1 | "K12" | FALSE | -1 |
| 2 | "B07" | FALSE | -1 |
| 3 | "M33" | FALSE | -1 |
| 4 | "A19" | FALSE | -1 |
| 5 | "T05" | TRUE | 5 |
Index at comparison; FoundAt after the IF.
T05 found at 5
Variations
- Search records: compare
Squad[Index].RunnerID. - Every match: use a
FORloop and output or count each match. - Sorted data: stop early once an element is greater than the target.
Why −1 and a conditional loop?
- −1 can never be a valid index, so it clearly means “not found”.
- The
WHILEsearch ends after the first match. With target B07, an unguardedFORloop reaches both matches: a match at 6 overwrites the index 2. GuardFoundAtagainst further updates, or stop at the first match.
Variations
- Search records: compare
Squad[Index].RunnerID. - Every match: use a
FORloop and output or count each match. - Sorted data: stop early once an element is greater than the target.
1 The target is "A19". How many elements are compared, and what is output?
2 The target is "B07", which is stored twice. What is output?
3 The target is "Z99". What is FoundAt when the loop ends, and why does the loop end?
- 14; A19 found at 4
- 2B07 found at 2: the WHILE test stops at the first match
- 3−1: Index reaches 9, so
Index <= 8is false after all eight are compared
Bubble sort: passes and swaps
A computer cannot glance at a list and see its order; it can only compare two values at a time. A bubble sort works through the array comparing adjacent pairs of values and swapping any pair in the wrong order. After each pass, the largest remaining value has moved to the end.
1DECLARE Pass, J, Temp : INTEGER 2FOR Pass ← 1 TO 5 3FOR J ← 1 TO 5 4IF Nums[J] > Nums[J + 1] THEN 5Temp ← Nums[J] 6Nums[J] ← Nums[J + 1] 7Nums[J + 1] ← Temp 8ENDIF 9NEXT J 10NEXT Pass
Describe it in steps
Trace pass 1 one comparison at a time
A swap needs a spare variable, Temp, or one of the two values is lost. Trace each swap, then give the array after each J.
| Line | Statement that runs | J | Temp | Nums[J] | Nums[J + 1] | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 3 | FOR J ← 1 TO 5 | 1 | J 1 | the first pair: elements 1 and 2 | |||
| the first pair: elements 1 and 2 | |||||||
| 4 | IF Nums[J] > Nums[J + 1] THEN | test 31 > 12 is true | |||||
| test 31 > 12 is true | |||||||
| 5 | Temp ← Nums[J] | 31 | Temp 31 | keep a copy of 31 | |||
| keep a copy of 31 | |||||||
| 6 | Nums[J] ← Nums[J + 1] | 12 | Nums[J] 12 | 12 moves into the first element; for a moment both hold 12 | |||
| 12 moves into the first element; for a moment both hold 12 | |||||||
| 7 | Nums[J + 1] ← Temp | 31 | Nums[J + 1] 31 | the copy in Temp goes into the second element | |||
| the copy in Temp goes into the second element | |||||||
J | Pair compared | Temp | Nums after this J | What happens | |
|---|---|---|---|---|---|
| J 1 | 1 | 31, 12 | 31 | 12 31 47 8 26 39 | 31 > 12: swap them |
| 31 > 12: swap them | |||||
| J 2 | 2 | 31, 47 | 12 31 47 8 26 39 | 31 > 47 is false: no swap | |
| 31 > 47 is false: no swap | |||||
| J 3 | 3 | 47, 8 | 47 | 12 31 8 47 26 39 | 47 > 8: swap them |
| 47 > 8: swap them | |||||
| J 4 | 4 | 47, 26 | 47 | 12 31 8 26 47 39 | 47 > 26: swap them |
| 47 > 26: swap them | |||||
| J 5 | 5 | 47, 39 | 47 | 12 31 8 26 39 47 | 47 > 39: swap them |
| 47 > 39: swap them | |||||
Three things to settle before writing a sort of your own: why Temp is needed, how to sort the other way, and how much work the basic version does.
The swap needs Temp
Temp keeps a copy of Nums[J] (31). Without it both elements end up holding 12 and 31 is lost. A procedure swapping its two arguments needs BYREF parameters.
Descending order
Change > to <. The same passes give 47 39 31 26 12 8: the smallest value moves to the end.
How much work?
Always (n − 1) passes of (n − 1) comparisons: 5 × 5 = 25 for six values, 999 × 999 = 998 001 for 1000, even if already sorted.
1 Nums holds 20, 14, 9, 30, 2, 17. Give the array after pass 1.
2 How many swaps happen in pass 1?
3 How many comparisons does this basic version make in total?
- 114, 9, 20, 2, 17, 30: 30 has moved to the end
- 24
- 325: 5 passes × 5 comparisons, even when sorted early
J with element J + 1, and stop the inner loop one before the upper bound so J + 1 stays inside the array. For descending order change > to < in the comparison.Bubble sort: the improved algorithm
The basic bubble sort keeps comparing long after the list is in order. The improved bubble sort stops as soon as a pass makes no swaps, and compares one pair fewer on each pass.
1DECLARE Boundary, J, Temp : INTEGER 2DECLARE NoSwaps : BOOLEAN 3Boundary ← 5 4REPEAT 5NoSwaps ← TRUE 6FOR J ← 1 TO Boundary 7IF Nums[J] > Nums[J + 1] THEN 8Temp ← Nums[J] 9Nums[J] ← Nums[J + 1] 10Nums[J + 1] ← Temp 11NoSwaps ← FALSE 12ENDIF 13NEXT J 14Boundary ← Boundary - 1 15UNTIL NoSwaps = TRUE
Why it is more efficient
Inner loop: the boundary shrinks
The inner loop iterates one less time on each pass, because each pass puts one more element (the largest remaining) in its correct place at the end. Those elements are not compared again.
Outer loop: the no-swap flag
The REPEAT loop stops as soon as a pass makes no swaps: the array is sorted, so no further passes are needed. If the data is already sorted, only one pass runs.
Trace: Nums = 31 12 47 8 26 39
Two values save the work: the no-swap flag and the boundary. Trace both pass by pass, and say why the loop stops.
| Line | Statement that runs | NoSwaps | J | Boundary | Writes | What happens |
|---|---|---|---|---|---|---|
| 5 | NoSwaps ← TRUE | TRUE | NoSwaps TRUE | assume sorted until a swap happens | ||
| assume sorted until a swap happens | ||||||
| 6 | FOR J ← 1 TO Boundary | 1 | J 1 | Boundary is 2 | ||
| Boundary is 2 | ||||||
| 7 | IF Nums[J] > Nums[J + 1] THEN | test 8 > 12 is false: no swap | ||||
| test 8 > 12 is false: no swap | ||||||
| 6 | FOR J ← 1 TO Boundary | 2 | J 2 | Boundary is 2 | ||
| Boundary is 2 | ||||||
| 7 | IF Nums[J] > Nums[J + 1] THEN | test 12 > 26 is false: no swap | ||||
| test 12 > 26 is false: no swap | ||||||
| 14 | Boundary ← Boundary - 1 | 1 | Boundary 1 | one fewer pair next time | ||
| one fewer pair next time | ||||||
| 15 | UNTIL NoSwaps = TRUE | test NoSwaps = TRUE is true: the loop ends | ||||
| test NoSwaps = TRUE is true: the loop ends | ||||||
Boundary | Compares | Swaps | NoSwaps | Nums after the pass | What happens | |
|---|---|---|---|---|---|---|
| start | 5 | 31 12 47 8 26 39 | line 3 | |||
| line 3 | ||||||
| pass 1 | 4 | 5 | 4 | FALSE | 12 31 8 26 39 47 | 4 swaps: NoSwaps is FALSE, so repeat with one fewer comparison |
| 4 swaps: NoSwaps is FALSE, so repeat with one fewer comparison | ||||||
| pass 2 | 3 | 4 | 2 | FALSE | 12 8 26 31 39 47 | 2 swaps: NoSwaps is FALSE, so repeat with one fewer comparison |
| 2 swaps: NoSwaps is FALSE, so repeat with one fewer comparison | ||||||
| pass 3 | 2 | 3 | 1 | FALSE | 8 12 26 31 39 47 | 1 swap: NoSwaps is FALSE, so repeat with one fewer comparison |
| 1 swap: NoSwaps is FALSE, so repeat with one fewer comparison | ||||||
| pass 4 | 1 | 2 | 0 | TRUE | 8 12 26 31 39 47 | no swaps: NoSwaps stays TRUE, so UNTIL ends the loop |
| no swaps: NoSwaps stays TRUE, so UNTIL ends the loop | ||||||
Trace: Nums = 31 12 47 8 26 39
| Pass | Comparisons | Swaps | NoSwaps at the end | Nums after the pass |
|---|---|---|---|---|
| 1 | 5 | 4 | FALSE | 12 31 8 26 39 47 |
| 2 | 4 | 2 | FALSE | 12 8 26 31 39 47 |
| 3 | 3 | 1 | FALSE | 8 12 26 31 39 47 |
| 4 | 2 | 0 | TRUE | 8 12 26 31 39 47 |
REPEAT loop ends after 14 comparisons. The basic version always makes 25.Comparisons made, basic against improved
The saving shows up as fewer comparisons on the same data.
| Six values | Basic comparisons | Improved passes | Improved comparisons |
|---|---|---|---|
31 12 47 8 26 39 as traced above | 25 | 4 | 14 |
8 12 31 26 39 47 nearly sorted | 25 | 2 | 9 |
8 12 26 31 39 47 already sorted | 25 | 1 | 5 |
Basic: comparisons. Improved: passes and comparisons.
| Six values | Basic | Passes | Compared |
|---|---|---|---|
31 12 47 8 26 39 as traced above | 25 | 4 | 14 |
8 12 31 26 39 47 nearly sorted | 25 | 2 | 9 |
8 12 26 31 39 47 already sorted | 25 | 1 | 5 |
1 Nums holds 3, 9, 4, 12, 15, 20. How many passes does the improved sort make?
2 What is Boundary when the loop ends?
3 How many comparisons are made in total? How many would the basic version make?
- 12: pass 1 swaps 9 and 4; pass 2 makes no swaps
- 23
- 39 (5 + 4); the basic version makes 25
Sorting arrays with associated data
Sort a list of race times on its own and every runner ends up with someone else’s time. When each value belongs with other data, such as a name with a race time, every swap must move all of that data.
The same rule in three structures: wherever the data lives, everything that belongs together is swapped inside the same IF.
DECLARE J, Boundary : INTEGER DECLARE TempTime : REAL DECLARE TempName : STRING DECLARE NoSwaps : BOOLEAN Boundary ← 4 REPEAT NoSwaps ← TRUE FOR J ← 1 TO Boundary IF Times[J] > Times[J + 1] THEN TempTime ← Times[J] Times[J] ← Times[J + 1] Times[J + 1] ← TempTime TempName ← Names[J] Names[J] ← Names[J + 1] Names[J + 1] ← TempName NoSwaps ← FALSE ENDIF NEXT J Boundary ← Boundary - 1 UNTIL NoSwaps = TRUE
DECLARE Temp : RunnerRecord IF Squad[J].BestTime > Squad[J + 1].BestTime THEN Temp ← Squad[J] Squad[J] ← Squad[J + 1] Squad[J + 1] ← Temp NoSwaps ← FALSE ENDIF
IF Points[Row, 2] > Points[Row + 1, 2] THEN FOR Col ← 1 TO 2 Temp ← Points[Row, Col] Points[Row, Col] ← Points[Row + 1, Col] Points[Row + 1, Col] ← Temp NEXT Col NoSwaps ← FALSE ENDIF
TempTime is REAL, TempName is STRING, and Temp for a record is a RunnerRecord. If the swap is written as a procedure, its two parameters must be BYREF, or only copies are swapped.1 After the sort, which name is in Names[1]?
2 Which name and time are in element 3 of the two arrays?
3 The three Names lines are left out of the swap. Which name is now next to 47.3?
- 1Ana: the shortest time, 47.3, is first
- 2Kofi, 50.0
- 3Lena: the names never move, so the times no longer match them
IF. With an array of records a single swap moves the whole record.Text files: storage, access modes and data types
Close a program and its variables are gone: variables and arrays exist in main memory only while the program runs. A text file on secondary storage keeps data between runs. It is a sequence of lines, each read or written as a string.
Open a file in one mode, then close it
Opening a file in the wrong mode can wipe it. Choose the mode from the task, and know what happens to the data already there.
| Mode | Use it to | Data already in the file |
|---|---|---|
READ | read lines with READFILE; test for the end with EOF() | unchanged |
WRITE | create a new file, then write lines with WRITEFILE | lost: the file starts empty |
APPEND | add lines after the existing data with WRITEFILE | kept |
One file, opened three times: follow which lines survive each mode, then check the output.
DECLARE Line : STRING OPENFILE "Log.txt" FOR WRITE WRITEFILE "Log.txt", "Started" CLOSEFILE "Log.txt" OPENFILE "Log.txt" FOR APPEND WRITEFILE "Log.txt", "Saved" CLOSEFILE "Log.txt" OPENFILE "Log.txt" FOR READ WHILE NOT EOF("Log.txt") READFILE "Log.txt", Line OUTPUT Line ENDWHILE CLOSEFILE "Log.txt"
Started Saved
Why files are needed
- Data is retained on non-volatile storage when the program ends or power is switched off.
- Data can be reused next time without re-entering it.
- The amount of data is not limited by an array's size, only by the storage available.
A text file holds only strings
- Convert numbers with
NUM_TO_STR()before writing andSTR_TO_NUM()after reading. - A BOOLEAN must be turned into text, e.g.
"Y"or"N". - Fields joined on one line need a separator that does not occur in those field values.
1 Log.txt holds the lines Started, Saved. It is opened FOR WRITE and "Closed" is written. What does it hold now?
2 It is opened FOR APPEND instead. What does it hold now?
3 Why is NUM_TO_STR() needed before a REAL is written?
- 1Closed: WRITE starts an empty file
- 2Started, Saved, Closed
- 3a text file holds only strings, so the number must be turned into text first
Reading a text file
A program cannot know in advance how many lines a file holds, so it reads until none are left. A text file is read one line per pass: test for the end of the file, read the next line as a STRING, then use or store it.
1DECLARE Names : ARRAY[1:100] OF STRING 2DECLARE Line : STRING 3DECLARE Count : INTEGER 4Count ← 0 5OPENFILE "Names.txt" FOR READ 6WHILE NOT EOF("Names.txt") 7READFILE "Names.txt", Line 8Count ← Count + 1 9Names[Count] ← Line 10ENDWHILE 11CLOSEFILE "Names.txt" 12OUTPUT Count, " names read"
Names.txtAsha Bilal Chen Dara
4 names read
Read the file one line per pass
Each pass first asks whether any lines are left. Trace the EOF test, the line read, and where it is stored.
| Line | Statement that runs | Line | Count | Names[Count] | Writes | What happens |
|---|---|---|---|---|---|---|
| 6 | WHILE NOT EOF("Names.txt") | test one line has been read and 3 are left: EOF is FALSE, so enter | ||||
| test one line has been read and 3 are left: EOF is FALSE, so enter | ||||||
| 7 | READFILE "Names.txt", Line | "Bilal" | Line "Bilal" | the next unread line; the file moves on one line | ||
| the next unread line; the file moves on one line | ||||||
| 8 | Count ← Count + 1 | 2 | Count 2 | the next element | ||
| the next element | ||||||
| 9 | Names[Count] ← Line | "Bilal" | Names[Count] "Bilal" | stored in Names[2] | ||
| stored in Names[2] | ||||||
EOF("Names.txt") | Line | Count | Names[Count] | What happens | |
|---|---|---|---|---|---|
| start | 0 | line 4; line 5 opens the file at its first line | |||
| line 4; line 5 opens the file at its first line | |||||
| pass 1 | FALSE | "Asha" | 1 | "Asha" | line 1 of the file goes into Names[1] |
| line 1 of the file goes into Names[1] | |||||
| pass 2 | FALSE | "Bilal" | 2 | "Bilal" | line 2 of the file goes into Names[2] |
| line 2 of the file goes into Names[2] | |||||
| pass 3 | FALSE | "Chen" | 3 | "Chen" | line 3 of the file goes into Names[3] |
| line 3 of the file goes into Names[3] | |||||
| pass 4 | FALSE | "Dara" | 4 | "Dara" | line 4 of the file goes into Names[4] |
| line 4 of the file goes into Names[4] | |||||
| end | TRUE | no line left: the loop ends; CLOSEFILE, then output “4 names read” | |||
| no line left: the loop ends; CLOSEFILE, then output “4 names read” | |||||
STR_TO_NUM() before using itDECLARE Line : STRING DECLARE Day, Steps : INTEGER Day ← 0 OPENFILE "Steps.txt" FOR READ WHILE NOT EOF("Steps.txt") READFILE "Steps.txt", Line Day ← Day + 1 Steps ← STR_TO_NUM(Line) IF Steps > 10000 THEN OUTPUT "Day ", Day, ": ", Steps ENDIF ENDWHILE CLOSEFILE "Steps.txt"
Steps.txt8450 12030 10000 15210 7020
Day 2: 12030 Day 4: 15210
Describe it in steps
- Open the file in read mode (close it after the loop).
- Set an index to 0.
- Until the end of the file, read a line into a string variable,
- add 1 to the index and store the line in the array at that index.
Why WHILE NOT EOF
- The test comes before each read: for an empty file
EOF()is TRUE at once and nothing is read (0 names read). - A
REPEATloop would try to read a missing line. EOF()never reads. To start again from line 1, close and reopen the file.
1 Steps.txt holds 9500, 10001, 10000, 12000, one per line. What does the second program output?
2 Why is STR_TO_NUM(Line) needed before the comparison?
3 Names.txt is empty. What does the first program output, and how many times does the loop body run?
- 1Day 2: 10001; Day 4: 12000: 10000 is not more than 10000
- 2
READFILEgives a STRING; the comparison with 10000 needs a number - 3“0 names read”; the body runs 0 times because EOF is TRUE at the first test
Text files: writing and appending
Saving the team means turning each record into one line of text. WRITEFILE writes one STRING per new line. WRITE starts an empty file; APPEND adds to its existing contents.
Team input (RunnerID, Name, BestTime, Paid), in index order: R0417, Mei Lin, 21.75, TRUE; R0388, Tomas Ruiz, 19.5, TRUE; R0452, Ada Okoro, 23.25, FALSE.
WRITE: one record per line, fields joined by a separator1CONSTANT Sep = '|' 2DECLARE Index : INTEGER 3DECLARE Line : STRING 4OPENFILE "Team.txt" FOR WRITE 5FOR Index ← 1 TO 3 6Line ← Team[Index].RunnerID & Sep & Team[Index].Name 7Line ← Line & Sep & NUM_TO_STR(Team[Index].BestTime) 8IF Team[Index].Paid THEN 9Line ← Line & Sep & "Y" 10ELSE 11Line ← Line & Sep & "N" 12ENDIF 13WRITEFILE "Team.txt", Line 14NEXT Index 15CLOSEFILE "Team.txt"
Team.txt after the programR0417|Mei Lin|21.75|Y R0388|Tomas Ruiz|19.5|Y R0452|Ada Okoro|23.25|N
NUM_TO_STR() turns the REAL into text and the BOOLEAN is written as Y or N. The separator | does not occur in these field values.
Build each line, then write it
A record has four fields of different types, but a line of text is a single string. Trace how one record becomes one line.
| Line | Statement that runs | Line | Team.txt | Writes | What happens |
|---|---|---|---|---|---|
| 6 | Line ← Team[Index].RunnerID & Sep & Team[Index].Name | "R0452|Ada Okoro" | Line "R0452|Ada Okoro" | ID, separator, name | |
| ID, separator, name | |||||
| 7 | Line ← Line & Sep & NUM_TO_STR(Team[Index].BestTime) | "R0452|Ada Okoro|23.25" | Line "R0452|Ada Okoro|23.25" | the REAL is turned into text first | |
| the REAL is turned into text first | |||||
| 8 | IF Team[Index].Paid THEN | test Team[3].Paid is FALSE: false, so the ELSE branch runs | |||
| test Team[3].Paid is FALSE: false, so the ELSE branch runs | |||||
| 11 | Line ← Line & Sep & "N" | "R0452|Ada Okoro|23.25|N" | Line "R0452|Ada Okoro|23.25|N" | the BOOLEAN is written as a text code | |
| the BOOLEAN is written as a text code | |||||
| 13 | WRITEFILE "Team.txt", Line | line 3 | Team.txt line 3 | one whole record per line | |
| one whole record per line | |||||
Index | Line written to Team.txt | What happens | |
|---|---|---|---|
| Index 1 | 1 | "R0417|Mei Lin|21.75|Y" | Paid is TRUE: “Y” is added; written as line 1 |
| Paid is TRUE: “Y” is added; written as line 1 | |||
| Index 2 | 2 | "R0388|Tomas Ruiz|19.5|Y" | Paid is TRUE: “Y” is added; written as line 2 |
| Paid is TRUE: “Y” is added; written as line 2 | |||
| Index 3 | 3 | "R0452|Ada Okoro|23.25|N" | Paid is FALSE: “N” is added; written as line 3 |
| Paid is FALSE: “N” is added; written as line 3 | |||
Waiting.txt already holds two names. APPEND keeps them and adds only the elements of NewNames that are in use.
APPEND: add only the elements that are in use// NewNames holds "Lena", "", "Raj", "", "", "Tom" DECLARE Index : INTEGER OPENFILE "Waiting.txt" FOR APPEND FOR Index ← 1 TO 6 IF NewNames[Index] <> "" THEN WRITEFILE "Waiting.txt", NewNames[Index] ENDIF NEXT Index CLOSEFILE "Waiting.txt"
Omar Priya
Omar Priya Lena Raj Tom
One field per line, or one record per line?
- A field per line avoids joining and splitting, but needs more file operations per record.
- A record per line needs fewer file operations, but must join and extract fields.
WRITE or APPEND?
APPEND keeps existing lines; WRITE replaces them. Open once before the loop: opening for WRITE on each pass erases the earlier output.
1 Tomas Ruiz has not paid (Paid is FALSE). What line is written for Index 2?
2 The second program opens Waiting.txt FOR WRITE instead of APPEND. What does the file hold afterwards?
3 With APPEND, how many lines does Waiting.txt hold afterwards?
- 1
R0388|Tomas Ruiz|19.5|N - 2Lena, Raj, Tom: WRITE started an empty file, so Omar and Priya are lost
- 35: the 2 already there and 3 new ones; empty strings are skipped
NUM_TO_STR() and give a BOOLEAN a text code. Open the file once before the loop (APPEND to keep existing data) and close it after the loop.Restoring records and searching a text file
Reading the team back undoes the saving: each line of text has to become a record again. Reading a line gives a STRING. Extract fields before assigning them to a record, and convert numeric or Boolean text to the field's declared type.
Extract(Line, Field) is supplied: it returns the numbered |-separated field of a line as a STRING. The first program restores the three saved records; the second searches a file of names and stops at the first match.
DECLARE Index : INTEGER DECLARE Line, TimeText : STRING OPENFILE "Team.txt" FOR READ FOR Index ← 1 TO 3 READFILE "Team.txt", Line Team[Index].RunnerID ← Extract(Line, 1) Team[Index].Name ← Extract(Line, 2) TimeText ← Extract(Line, 3) Team[Index].BestTime ← STR_TO_NUM(TimeText) Team[Index].Paid ← Extract(Line, 4) = "Y" NEXT Index CLOSEFILE "Team.txt"
1DECLARE Line, Target : STRING 2DECLARE Position, FoundAt : INTEGER 3INPUT Target 4Position ← 0 5FoundAt ← -1 6OPENFILE "Names.txt" FOR READ 7WHILE NOT EOF("Names.txt") AND FoundAt = -1 8READFILE "Names.txt", Line 9Position ← Position + 1 10IF TO_LOWER(Line) = TO_LOWER(Target) THEN 11FoundAt ← Position 12ENDIF 13ENDWHILE 14CLOSEFILE "Names.txt" 15OUTPUT FoundAt
Trace the search for CHEN
Searching a file is a linear search that reads as it goes. For each line read, trace the comparison, Position and FoundAt.
Line | TO_LOWER(Line) | Position | FoundAt | What happens | |
|---|---|---|---|---|---|
| start | 0 | −1 | lines 4 to 6: nothing read yet | ||
| lines 4 to 6: nothing read yet | |||||
| pass 1 | "Asha" | "asha" | 1 | "asha" ≠ "chen": read on | |
| "asha" ≠ "chen": read on | |||||
| pass 2 | "Bilal" | "bilal" | 2 | "bilal" ≠ "chen": read on | |
| "bilal" ≠ "chen": read on | |||||
| pass 3 | "Chen" | "chen" | 3 | 3 | "chen" = "chen": FoundAt ← 3 |
| "chen" = "chen": FoundAt ← 3 | |||||
| end | FoundAt is no longer −1: the WHILE test fails, so Dara is never read | ||||
| FoundAt is no longer −1: the WHILE test fails, so Dara is never read | |||||
The same saved record, restored
R0417|Mei Lin|21.75|Y
Extract(Line, Field) is supplied: it returns the numbered |-separated field as a STRING. This file has exactly three complete valid records, in the saved order. Fields 3 and 4 become REAL 21.75 and BOOLEAN TRUE; they do not stay text.
Trace the search's stopping point
Names.txt contains Asha, Bilal, Chen, Dara, one per line. Input CHEN matches line 3 after case conversion. FoundAt becomes 3; the next test ends the loop without reading Dara. An absent name leaves FoundAt=-1 after EOF.
Describe the file search without pseudocode
1 The input is "dara". What is output?
2 The input is "Eve". What is output, and how many lines are read?
3 Field 3 of a line is "21.75". What must happen before it is stored in BestTime, and why?
- 14: the case is ignored
- 2-1; all 4 lines are read before EOF ends the loop
- 3convert it with
STR_TO_NUM(): every field extracted from a line is a STRING, and BestTime is REAL
Abstract data types
Stacks, queues and linked lists are known by what they do, not by how they are built. An abstract data type (ADT) bundles data with a set of operations that can be carried out on it.
Key features and when to use each
Choosing an ADT means matching how it behaves to what the situation needs. Give two features of each.
| ADT | Key features | Justify it when… |
|---|---|---|
| Stack | Last in, first out (LIFO). A pointer to the top (some designs add a bottom pointer or an item count). Items are pushed and popped only at the top. | the most recent item must be dealt with first: undo, a browser’s back button, reversing a list |
| Queue | First in, first out (FIFO). A front pointer and a rear pointer. Added at the rear, removed from the front. Can be circular. | items must be dealt with in arrival order: print jobs, a keyboard buffer, requests to a server |
| Linked list | Each node holds data and a pointer to the next node. A start pointer; the last node has a null pointer; unused nodes are kept on a free list. Its logical length changes as nodes are added or removed. | data must stay in order with frequent insertions and deletions: existing data stays in place; the links change |
Printer jobs: arrival order to output
Linked list or array?
- For a linked list: update links to insert or delete in order.
- Against: pointers take extra storage, and it is more complex to set up.
1 Customers are served in the order they join a waiting list. Which ADT fits, and why?
2 An editor must undo the most recent change first. Which ADT fits, and why?
3 Names are kept in alphabetical order, and names are often added and removed. Which ADT fits, and why?
- 1a queue: first in, first out keeps arrival order
- 2a stack: last in, first out gives the newest change first
- 3a linked list: a new node is linked into place by changing pointers; no data is moved
A stack in an array
Undo works like a pile of plates: the last thing added is the first taken off. A stack uses an array Stack[1:8] and an integer Top that holds the index of the last item added. Top = 0 means the stack is empty.
Amber: pushed in that group. Grey, in brackets: popped. A popped value may stay in the array, but it is above Top, so it is not on the stack and the next push overwrites it: the array needs no initial values.
PUSH an item
Top = 8, report an error and stop.Top.Stack[Top].POP an item
Top = 0, report an error and stop.Stack[Top].Top.Implementing a stack with an array
- A 1D array of the item’s data type, one element per item the stack can hold.
- An integer top-of-stack pointer used as the array index, and the maximum size.
- Initialise the pointer to show an empty stack:
Top ← 0. - Push and pop check for full and empty first.
Two ways to design Top
| Pointer design | Empty | Full | Push |
|---|---|---|---|
Top: last item added | 0 | 8 | add 1, store |
SP: next free element | 1 | 9 | store, add 1 |
Some designs also keep a bottom pointer, or a count of items (empty 0, full 8). A stack can grow towards lower addresses: then a push subtracts 1.
1 After group 3, PUSH 'X', PUSH 'Y', POP run. What does the POP return?
2 What is Top now, and what is still stored in Stack[5]?
3 Top = 8. What must PUSH do before it changes anything?
- 1'Y'
- 2Top = 4;
Stack[5]still holds 'Y', but it is above Top, so it is not on the stack - 3report that the stack is full and stop: Top = 8 is the upper bound
A circular queue in an array
In a queue the first to arrive is the first served. Shuffling every item forward after each removal wastes time, so in a circular queue the pointers move instead. It uses Queue[1:6]. Front is the index of the next item to remove, Rear the index of the last item added, and NumItems counts the items.
Amber: added in that step. Grey, in brackets: already removed. Nothing is shuffled forward, as it would be in a design that shifts items: the circular design reuses freed elements (J7 goes into element 3).
After step 3 the queue, read from Front and wrapping from 6 to 1, is J3, J4, J5, J6, J7.
DECLARE Queue : ARRAY[1:6] OF STRING DECLARE Front, Rear, NumItems : INTEGER Front ← 1 Rear ← 0 NumItems ← 0
Each operation is a short sequence, and the check comes first: never add to a full queue or remove from an empty one.
| Step | ENQUEUE: add an item | DEQUEUE: remove an item |
|---|---|---|
| 1 | if NumItems = 6 the queue is full: stop | if NumItems = 0 the queue is empty: stop |
| 2 | add 1 to Rear; if it passes 6, set it to 1 (wrap around) | copy the item from Queue[Front] |
| 3 | store the item in Queue[Rear]; add 1 to NumItems | add 1 to Front (wrap around); subtract 1 from NumItems |
Two ways to design Rear
Rear holds the index of | Add an item | Rear after step 3 |
|---|---|---|
| the last item added (as in the steps) | add 1 to Rear (wrap), then store | 3 |
| the next free element | store, then add 1 to Rear (wrap) | 4 |
With all six elements in use, the queue is full when NumItems = 6. With this last-item Rear, Front = Rear means one item. A different design can use a next-free Rear and reserve one element: empty when Front = Rear, full when advancing Rear would reach Front. That design holds at most five items.
- All six elements are used, so the queue is full when
NumItems = 6. - With this last-item
Rear,Front = Rearmeans one item. - A different design uses a next-free
Rearand reserves one element: empty when Front = Rear, full when advancing Rear would reach Front. It holds at most five items.
1 From the step 4 state, two DEQUEUE operations run. Which items are removed?
2 What is Front after them?
3 Then ENQUEUE J10 runs. Which element does J10 go into, and what is NumItems?
- 1J3, J4: the front items
- 21: 6 wraps round to 1
- 3element 5, freed when J3 was removed; NumItems = 5
Linked lists in arrays
Keep names in alphabetical order in an ordinary array, and every new name shuffles the later ones along. In a linked list each node holds an item and a pointer to the next node, so nothing has to shift; the start pointer gives the first node and the last holds the null pointer, here 0.
Each node holds an item and a pointer to the next node, so nothing has to shift. The start pointer gives the first node; the last node holds the null pointer, here 0. Unused nodes form the free list.
Follow the pointers from Start to read the list in order; unused nodes form the free list. A node's index is where it sits in both arrays.
Traverse the list
Current to the start pointer.Current is not the null pointer (0), repeat steps 3 and 4.Data[Current].Current to Pointer[Current].Here Current takes the values 4 → 2 → 3 → 1 → 0 and the output is Date, Fig, Lime, Plum.
DECLARE Data : ARRAY[1:7] OF STRING DECLARE Pointer : ARRAY[1:7] OF INTEGER DECLARE StartPointer, FreePointer : INTEGER DECLARE Index : INTEGER FOR Index ← 1 TO 6 Pointer[Index] ← Index + 1 NEXT Index Pointer[7] ← 0 StartPointer ← 0 FreePointer ← 1
Implementing a linked list with arrays
- Two 1D arrays:
Datafor the items andPointer(INTEGER) for the links; the same index in both is one node. - Or one 1D array of a record type whose two fields hold the item and its pointer.
- Integer variables for the start pointer and the free list pointer.
- A null value that is not a valid index: 0 when the lower bound is 1, −1 when it is 0.
1 Follow the pointers from Start. In what order are the nodes visited, as indexes?
2 Which node is the next new item stored in?
3 What does Pointer[1] hold, and what does that tell you?
- 14 → 2 → 3 → 1, then 0
- 2node 5: Free points to it
- 30: node 1 (Plum) is the last node of the list
Linked lists: insert and delete
Putting a new item in the middle of a list is where pointers earn their keep. Insertion stores new data in a free node and changes links. Deletion bypasses a node and returns it to the free list; existing data need not move.
Kiwi goes into free node 5, then Lime is deleted. After each change, follow Next from Start to check the order; only the pointers change.
Insert Kiwi in order
Data[5]; Free ← Pointer[5] = 6.Pointer[5] ← 3: Kiwi points to Lime.Pointer[2] ← 5: Fig points to Kiwi.Delete Lime
Pointer[5] ← Pointer[3] = 1: Kiwi now points to Plum, bypassing Lime.Pointer[3] ← Free (6), then Free ← 3.Special cases
- Inserting or deleting at the front: change the start pointer.
- Deleting the last node: the node before it gets the null pointer.
- Empty list: insert makes the new node Start; delete finds nothing. Missing item: report it without changing links.
- Deleting the only item: set Start to null and return that node to Free.
- No free node (free pointer null): the list is full.
Edit, then check
Edit: find the node and change its data. If the new value belongs elsewhere in the order, delete the node and insert the new value.
Check: follow the pointers from Start. Every item appears once, in order, ending at the null pointer.
1 After deleting Lime, “Apple” is inserted. Which node is it stored in?
2 Apple comes before Date. Which pointer changes to link it in, and to what?
3 What is Free afterwards?
- 1node 3: the first free node, where Lime’s old data still sits
- 2the start pointer: Start ← 3, and
Pointer[3]← 4 (Date) - 36
Stacks and queues: applications and data order
Programs often move data from one structure to another: from a stack to a file, or from a file to a queue. Each move can keep the order or change it. The ADT you choose decides the order in which data comes back out.
Reverse a stack using a queue
Save a stack to a text file
The file holds S, R, Q, P: the top item comes first.
Back and forward buttons: two stacks
Pages visited: home, news, sport. Back pushes the page shown onto the forward stack, then pops the back stack to show. Forward is the reverse. Stacks read bottom to top.
| Back stack | Shown | Forward stack | What happens | |
|---|---|---|---|---|
| start | home news | sport | empty | three pages visited; Back holds the earlier two |
| three pages visited; Back holds the earlier two | ||||
| Back | home | news | sport | Back: push sport onto Forward, pop news from Back |
| Back: push sport onto Forward, pop news from Back | ||||
| Back | empty | home | sport news | Back: push news onto Forward, pop home from Back |
| Back: push news onto Forward, pop home from Back | ||||
| Forward | home | news | sport | Forward: push home onto Back, pop news from Forward |
| Forward: push home onto Back, pop news from Forward | ||||
Stack or queue for this job?
Lines of a file are stored in an ADT, then written to a new file.
stack: Line 3, Line 2, Line 1
queue: Line 1, Line 2, Line 3
The stack reverses them, as the last line added is the first removed. The queue keeps the original sequence: first in, first out.
Back and forward buttons: two stacks
Pages visited: home, news, sport. Back pushes the page shown onto the forward stack, then pops the back stack to show. Forward is the reverse. Stacks read bottom to top.
| Click | Back stack | Shown | Forward |
|---|---|---|---|
| start | home news | sport | empty |
| Back | home | news | sport |
| Back | empty | home | sport news |
| Forward | home | news | sport |
Stack or queue for this job?
Lines of a file are stored in an ADT, then written to a new file.
stack: Line 3, Line 2, Line 1
queue: Line 1, Line 2, Line 3
The stack reverses them, as the last line added is the first removed. The queue keeps the original sequence: first in, first out.
1 A stack holds A, B, C from bottom to top. It is saved to a file by popping until empty. In what order are the lines written?
2 Those items are then added to a queue in that order and removed until it is empty. In what order do they come out?
3 Which ADT reverses the order of the data it is given?
- 1C, B, A: the top item first
- 2C, B, A: a queue keeps the order it was given
- 3a stack: the last item in is the first out