Skip to content

9618 · Unit 10 · Paper 2: Problem-solving and programming

Data types and structures.

9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Choosing a data type

§10.1 · Data types and records · selecting data types

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.

Only TRUEor FALSE?noyesBOOLEANFALSEA calendar date,written without quotes?noyesDATE03/09/2024A whole number forcounting or arithmetic?noyesINTEGER42A number that canhave a fractional part?noyesREAL4.75Text that is exactlyone character?yesCHAR'Y'noSTRING"0712"Ask the questions in order, starting with TRUE or FALSE. The first “yes” gives the type; text that fails every test is a STRING.
TRUE or FALSE only?yesBOOLEANFALSEnoCalendar date, not quoted text?yesDATE03/09/2024noWhole number used in arithmetic?yesINTEGER42noNumber with a fractional part?yesREAL4.75noText of exactly one character?yesCHAR'Y'Otherwise STRING, e.g. "0712"

How to choose a type

Ask what the program will do with the value, and the type follows from the answer.

Value or useTypeWhy
"03/09/2024" in quotesSTRINGthe quotes make it text, not a date
03/09/2024, no quotesDATEan unquoted date value, or a date used in calculations
"0712 345678", a phone numberSTRINGkeeps the leading 0; never used in arithmetic
Total / CountREAL/ always gives a REAL, even for two integers
LEFT(Code, 1)CHARexactly one character (a STRING also works)
Mark >= 50BOOLEANa comparison is either TRUE or FALSE
Index, a position in an arrayINTEGERan index is always a whole number
A number is not a string
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 normally dd/mm/yyyy, so state the format you use
Your turn

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?

  1. 1
    INTEGER: a whole number used in arithmetic
  2. 2
    REAL: / always gives a REAL
  3. 3
    STRING: a number type would drop the zeros, and it is never used in arithmetic
  4. 4
    BOOLEAN
Tick what you can do now
Exam focusGive the pseudocode keyword exactly: 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.
Practise with s24/21 Q1(a); w24/23 Q1(b); s25/23 Q1(c); w25/22 Q1(b); s25/22 Q1(c)
1 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Records: one identifier, many types

§10.1 · Data types and records · record structures

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.

Define the type, declare a variable, write and read fields
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
The variable Runner after the assignmentsvariable . fieldtypevalueRunner.RunnerIDSTRING"R0417"Runner.NameSTRING"Mei Lin"Runner.AgeINTEGER16Runner.BestTimeREAL21.75Runner.CategoryCHAR'J'Runner.PaidBOOLEANFALSERunner.JoinedDATE03/09/2024One identifier, seven fields, six different data types.
Runner: one variable, seven fieldsRunner.RunnerIDSTRING"R0417"Runner.NameSTRING"Mei Lin"Runner.AgeINTEGER16Runner.BestTimeREAL21.75Runner.CategoryCHAR'J'Runner.PaidBOOLEANFALSERunner.JoinedDATE03/09/2024

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

ExampleTypeExampleType
"L2207"STRING2INTEGER
0.75REAL'R'CHAR
FALSEBOOLEAN14/10/2026DATE
Your turn

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. 1
    DECLARE Laps : INTEGER
  2. 2
    Runner.Age ← Runner.Age + 1
  3. 3
    RunnerRecord is the type, which holds no data; use the variable: Runner.Name ← "Ada"
Tick what you can do now
Exam focusDefine the type with 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.
Practise with s24/22 Q3(a)(i); w25/21 Q3(a)(i); s23/21 Q3(a)(i) (older paper: record choice and advantage)
2 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Arrays of records

§10.1 §10.2 · Records · 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 : ARRAY[1:50] OF RunnerRecordRunnerIDNameAgePaidBestTime1R0417Mei Lin16TRUE21.752R0388Tomas Ruiz17TRUE19.53""––––4R0452Ada Okoro15FALSE23.255R0390Sam Patel16TRUE20.5…50""––––Squad[4].BestTime = 23.25the index picks the record, the dot picks the fieldunused element: RunnerID holds the empty stringelements 6 to 50 are unused in the same way

Squad[1:50]: each index selects the same record in both panels.

IndexRunnerIDName
1R0417Mei Lin
2R0388Tomas Ruiz
3""unused
4R0452Ada Okoro
5R0390Sam Patel
6–50""unused
IndexAgePaidBestTime
116TRUE21.75
217TRUE19.5
3———
415FALSE23.25
516TRUE20.5
6–50———
Squad[4].BestTime = 23.25: index 4 selects Ada's record; the dot selects BestTime.
Process every used record in a loop
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
Output
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

NameBestTime1Mei Lin21.752Tomas Ruiz19.53""–4Ada Okoro23.25same index= same runnerName : ARRAY[1:50] OF STRINGBestTime : ARRAY[1:50] OF REAL
IndexNameBestTime
1Mei Lin21.75
2Tomas Ruiz19.5
3""—
4Ada Okoro23.25

The same index links the name and time in the two parallel arrays.

Your turn

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. 1
    "Tomas Ruiz"
  2. 2
    1, 2, 4, 5; Count = 4
  3. 3
    Mean best time: 21.5: (21.75 + 19.5 + 23.25) ÷ 3
Tick what you can do now
Exam focusDeclare it as 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.
Practise with s24/22 Q3(a)(ii), (b); w25/21 Q3(b); s22/23 Q5(b)(ii) (older paper: unused-record marker)
3 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Arrays: index, bounds and dimensions

§10.2 · Arrays · technical terms and declarations

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.

Temps : ARRAY[1:7] OF REAL18.5121.0219.5323.0422.5517.0620.07Temps[4]lower bound 1upper bound 7index (subscript)7 elements, all REAL, under one identifier.Seat : ARRAY[1:3, 1:5] OF CHARsecond index: column123451XXX2X3XXfirst index:rowSeat[2, 4] = 'X'3 rows × 5 columns = 15 elements
Temps : ARRAY[1:7] OF REAL18.5121.0219.5323.0422.5517.0620.07lower bound 1upper bound 7Temps[4]Seat : ARRAY[1:3, 1:5] OF CHARsecond index: column123451X..XX2...X.3XX...first index: row · Seat[2, 4] = 'X'3 × 5 = 15 elements; each element is CHAR

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 STRING
30 − 1 + 1 = 301 dimension
DECLARE Hits : ARRAY[0:9] OF INTEGER
9 − 0 + 1 = 101 dimension
DECLARE Seat : ARRAY[1:3, 1:5] OF CHAR
3 × 5 = 152 dimensions
DECLARE Usage : ARRAY[0:23, 1:7] OF REAL
24 × 7 = 1682 dimensions
To declare an array you need its identifier, the lower and upper bound of each dimension and the data type of the elements. Elements per dimension = upper bound − lower bound + 1.

The 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.
Your turn

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.

  1. 1
    12: 11 − 0 + 1
  2. 2
    40: 4 rows × 10 columns
  3. 3
    DECLARE Names : ARRAY[1:20] OF STRING
Tick what you can do now
Exam focusCopy the declaration format exactly: 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.
Practise with s25/22 Q1(d)(i), (d)(ii), (d)(iii); s26/23 Q8(a)(i); w24/22 Q2(b)(i)
4 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Choosing and processing 1D arrays

§10.2 · Arrays · selecting and processing 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 storeStructureReason
the names of 30 studentsARRAY[1:30] OF STRINGone list of one type: 1D
rainfall for 52 weeks × 7 daysARRAY[1:52, 1:7] OF REALtwo indexes, week and day: 2D
20 × 30 seats, booked or notARRAY[1:20, 1:30] OF BOOLEANtwo indexes, row and seat: 2D
a name and a score per studentarray of records, or two 1D arraystwo 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.

One pass: total, count and largest
 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
0.014.5212.030.043.550.067.07Rain : ARRAY[1:7] OF REALshaded: wet days · blue: the wettest day
Rain : ARRAY[1:7] OF REAL0.014.5212.030.043.550.067.07Shaded: wet days · blue: wettest day
Output
Total: 27.0
Wet days: 4
Wettest day: 3
Initialise every element
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.

Pass 3, line by line: Day = 3
Together these lines make the blue row of the table below.
LineStatement that runsDayTotalWetDaysWettestWritesWhat happens
6FOR Day ← 1 TO 73Day 3the third time round the loop
the third time round the loop
7Total ← Total + Rain[Day]16.5Total 16.54.5 + 12.0 = 16.5
4.5 + 12.0 = 16.5
8IF Rain[Day] > 0.0 THENtest 12.0 > 0.0 is true
test 12.0 > 0.0 is true
9WetDays ← WetDays + 12WetDays 2one more wet day
one more wet day
11IF Rain[Day] > Rain[Wettest] THENtest 12.0 > Rain[2], which is 4.5: true
test 12.0 > Rain[2], which is 4.5: true
12Wettest ← Day3Wettest 3remember the index, not the value
remember the index, not the value
DayRain[Day]TotalWetDaysWettestWhat happens
start0.001lines 3 to 5, before the loop
lines 3 to 5, before the loop
pass 110.00.00.0: not a wet day
0.0: not a wet day
pass 224.54.5124.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 3312.016.52312.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 440.016.50.0: not a wet day
0.0: not a wet day
pass 553.520.033.5 > 0.0: a wet day
3.5 > 0.0: a wet day
pass 660.020.00.0: not a wet day
0.0: not a wet day
pass 777.027.047.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 7 for ARRAY[1:7], 0 TO 6 for ARRAY[0:6].
Your turn

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?

  1. 1
    28.0
  2. 2
    5
  3. 3
    4: the test is >, so the equal value on day 6 does not replace it
Tick what you can do now
Exam focusInitialise totals and counters before the loop, update them inside it and output after it. The loop counter is the index, and its range must match the declared bounds.
Practise with s24/23 Q4(b)(i), (b)(ii); s25/22 Q7(c)(i)
5 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Tracing strings inside an array

§10.2 · Arrays · mutations and retained values

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.

One array element changes per iteration
 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.

Index = 3, line by line
The blue row of the table below.
LineStatement that runsIndexCLimitLabels[3]WritesWhat happens
8FOR Index ← 1 TO 33Index 3the last pass
the last pass
9C ← MID(Modes, Index, 1)'?'C '?'character 3 of "UL?"
character 3 of "UL?"
10Limit ← Limits[Index]4Limit 4Limits[3]
Limits[3]
11CASE OF Ctest '?' is not 'U', 'L' or 'P': no branch runs
test '?' is not 'U', 'L' or 'P': no branch runs
16Labels[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
CLimitResultLabels[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
CLimitResultLabels[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.

Initial stateResult = "hold"123456789101Mei Lin2Tomas Ruiz3Ada Okoro
After Index = 1C = 'U' · Limit = 3Result = "MEI LIN"123456789101MEI2Tomas Ruiz3Ada Okoro
After Index = 2C = 'L' · Limit = 5Result = "tomas ruiz"1234567891MEI2tomas3Ada Okoro
After Index = 3C = '?' · Limit = 4Result = "tomas ruiz"123451MEI2tomas3toma
SnapshotCLimitResultLabels[1]Labels[2]Labels[3]
Initial state——"hold""Mei Lin""Tomas Ruiz""Ada Okoro"
After Index = 1U3"MEI LIN""MEI""Tomas Ruiz""Ada Okoro"
After Index = 2L5"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".

Your turn

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. 1
    "#K": "#" & "Kai Moss", then the first 2 characters
  2. 2
    "lu che"
  3. 3
    "INE"
  4. 4
    "INES ROY": Result keeps the whole string; only the stored copy is cut
Tick what you can do now
Exam focusFollow assignments in execution order. Do not reset a variable unless the algorithm does; array elements not assigned keep their values.
Practise with s24/21 Q5(a)
6 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Tracing an array: copying the values that pass a test

§10.2 · Arrays · conditional assignment

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.

Stage 1: build a compact used prefix
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
Completed state: Count = 5
Nums131212347not copied48526639
Pickedcopied at131J = 1212J = 238J = 4426J = 5539J = 66–unused
the used prefix, Picked[1] to Picked[Count]failed the test: skippednever written

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.

J = 4, line by line: the first value after the skip
The blue row of the table below.
LineStatement that runsJCountPicked[Count]WritesWhat happens
4FOR J ← 1 TO 64J 4the fourth Nums element
the fourth Nums element
5IF Nums[J] < 40 THENtest Nums[4] is 8: 8 < 40 is true
test Nums[4] is 8: 8 < 40 is true
6Count ← Count + 13Count 3the next free position in Picked
the next free position in Picked
7Picked[Count] ← Nums[J]8Picked[Count] 8so 8 goes into Picked[3], not Picked[4]
so 8 goes into Picked[3], not Picked[4]
JNums[J]CountPicked[Count]What happens
start0line 3: no value copied yet
line 3: no value copied yet
J 113113131 < 40: Picked[1] ← 31
31 < 40: Picked[1] ← 31
J 221221212 < 40: Picked[2] ← 12
12 < 40: Picked[2] ← 12
J 334747 < 40 is false: nothing is written
47 < 40 is false: nothing is written
J 448388 < 40: Picked[3] ← 8
8 < 40: Picked[3] ← 8
J 552642626 < 40: Picked[4] ← 26
26 < 40: Picked[4] ← 26
J 663953939 < 40: Picked[5] ← 39
39 < 40: Picked[5] ← 39
Stage 1: build a compact used prefix
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

JNums[J]Count after IFArray assignment
1311Picked[1] = 31
2122Picked[2] = 12
3472—
483Picked[3] = 8
5264Picked[4] = 26
6395Picked[5] = 39

Completed state: Count = 5

Index123456
Nums31124782639
Picked311282639unused

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].

Picked[6] is unused. Count bounds the used prefix; its unused element must not be read as a selected value.
Your turn

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?

  1. 1
    12, 39, 7: 45, 40, 52 fail the test (40 < 40 is false)
  2. 2
    3
  3. 3
    J = 3
Tick what you can do now
Exam focusTrace the condition before the assignment. A blank assignment cell means no array write, not an empty stored value.
Practise with s26/23 Q7(a)(i)
7 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Tracing an array: searching it backwards

§10.2 · Arrays · indexed reads

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.

Carried from stage 1: Count = 5
Picked13121238426even539odd6–unused
carried in, not readread and rejectedread and found

Starting state: Count = 5

Index123456
Nums31124782639
Picked311282639unused
Stage 2: read the final state of stage 1
 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.

The first pass, line by line: Pos = 5
Together these lines make the blue row of the table below.
LineStatement that runsPosFoundWritesWhat happens
6IF Picked[Pos] MOD 2 = 0 THENtest 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
9Pos ← Pos - 14Pos 4the ELSE branch moves back one element
the ELSE branch moves back one element
11UNTIL Found OR Pos = 0test Found is FALSE and Pos is not 0: false, so repeat
test Found is FALSE and Pos is not 0: false, so repeat
PosPicked[Pos]FoundWhat happens
start5FALSElines 3 and 4: start at the last used element
lines 3 and 4: start at the last used element
Pos 543939 MOD 2 = 1: odd, so Pos ← 4
39 MOD 2 = 1: odd, so Pos ← 4
Pos 426TRUE26 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
Stage 2: read the final state of stage 1
 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 testPicked[Pos]Found after test
539FALSE
426TRUE

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.

This REPEAT loop assumes Count > 0. If stage 1 can choose no values, check Count before entering. These snapshots show Pos at each test, before a possible decrement.
Your turn

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?

  1. 1
    22
  2. 2
    3: 3 and 7 are odd, then 22 is even
  3. 3
    "No even value"; Pos is 0, so the UNTIL test ends the loop
Tick what you can do now
Exam focusCarry the final state into the next stage. Moving Pos changes the selected position; it does not move or delete an array element.
Practise with s26/23 Q7(b)(i)
8 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Processing 2D arrays

§10.2 · Arrays · nested loops over rows and columns

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.

Sales : ARRAY[1:3, 1:4] OF INTEGERQtr (second index, column)1234row total112159205628111410433176131854Shop(row)column total37323648Sales[2, 3] = 14: shop 2, quarter 3Outer loop: one row (shop) at a time.Inner loop: every column (quarter) of that row.Row total: reset to 0 at the start of each row,output after the inner loop has finished.Column totals: swap the two loops, so theouter loop steps through the columns.
Sales[shop, quarter]1234total11215920562811141043317613185437323648Sales[2, 3] = 14Row total: reset for each shop.Inner loop visits its four quarters.Column totals: visit all shops per quarter.
Row totals: nested loops
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
Output
Shop 1: 56
Shop 2: 43
Shop 3: 54
Column totals: loops swapped
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
Output
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.

Shop = 2, line by line: the inner loop runs four times
The blue row of the table below.
LineStatement that runsShopQtrTotalOutputWritesWhat happens
2FOR Shop ← 1 TO 32Shop 2the second row
the second row
3Total ← 00Total 0a fresh total for this row
a fresh total for this row
4FOR Qtr ← 1 TO 41Qtr 1column 1 of row 2
column 1 of row 2
5Total ← Total + Sales[Shop, Qtr]8Total 8+ Sales[2, 1], which is 8
+ Sales[2, 1], which is 8
4FOR Qtr ← 1 TO 42Qtr 2column 2 of row 2
column 2 of row 2
5Total ← Total + Sales[Shop, Qtr]19Total 19+ Sales[2, 2], which is 11
+ Sales[2, 2], which is 11
4FOR Qtr ← 1 TO 43Qtr 3column 3 of row 2
column 3 of row 2
5Total ← Total + Sales[Shop, Qtr]33Total 33+ Sales[2, 3], which is 14
+ Sales[2, 3], which is 14
4FOR Qtr ← 1 TO 44Qtr 4column 4 of row 2
column 4 of row 2
5Total ← Total + Sales[Shop, Qtr]43Total 43+ Sales[2, 4], which is 10
+ Sales[2, 4], which is 10
7OUTPUT "Shop ", Shop, ": ", TotalShop 2: 43Output Shop 2: 43after the inner loop ends
after the inner loop ends
ShopSales[Shop, Qtr], Qtr 1 to 4Total after eachOutputWhat happens
Shop 1112, 15, 9, 2012 → 27 → 36 → 56Shop 1: 56Total reset to 0, then 4 additions; output after NEXT Qtr
Total reset to 0, then 4 additions; output after NEXT Qtr
Shop 228, 11, 14, 108 → 19 → 33 → 43Shop 2: 43Total reset to 0, then 4 additions; output after NEXT Qtr
Total reset to 0, then 4 additions; output after NEXT Qtr
Shop 3317, 6, 13, 1817 → 23 → 36 → 54Shop 3: 54Total 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 placedOutput for shops 1, 2, 3
inside the outer loop, before the inner loop56, 43, 54 ✓ correct
before both loops (only once)56, 99, 153 running totals
inside the inner loop, before the addition20, 10, 18 only the last quarter
Your turn

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?

  1. 1
    17: row 3, column 1
  2. 2
    the Qtr loop: one column at a time
  3. 3
    Qtr 2: 69: the Qtr 1 total, 37, is carried on and 32 is added
Tick what you can do now
Exam focusUse both indexes in the order the question defines, e.g. 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].
Practise with s26/22 Q6(b)(i), Q6(b)(ii); s25/21 Q6(b)
9 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Reports from selected array elements

§10.2 · Arrays · conditions and output scope

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.

Sales : ARRAY[1:3, 1:4] OF INTEGERQtr (second index, column)1234row total112159205628111410433176131854Shop(row)column total37323648
Sales[shop, quarter]1234total11215920562811141043317613185437323648Sales[2, 3] = 14Row total: reset for each shop.Inner loop visits its four quarters.Column totals: visit all shops per quarter.

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.

One row: Shop is input once
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"
With Shop = 1
Quarter 2
Quarter 4
2 high quarters
Every row: one header per shop
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"
Output
Shop 1
Quarter 2
Quarter 4
Shop 2
Shop 3
Quarter 1
Quarter 4
4 high quarters overall
Shop 2 has no value >= 15. Its header still appears, because the header is outside the IF. For the overall count, initialise before both loops and output after both; resetting inside the outer loop would count each shop separately.
Your turn

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?

  1. 1
    Quarter 1; Quarter 4; 2 high quarters
  2. 2
    2 high quarters overall: only 20 and 18 reach 18
  3. 3
    the header is output inside the outer loop but outside the IF, so it runs once for every shop
Tick what you can do now
Practise with s26/21 Q9(b); s26/23 Q8(a)(ii)
10 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Bubble sort: passes and swaps

§10.2 · Arrays · sorting with a bubble sort

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.

Pass 1, one comparison at a time112233445566start31124782639J = 112314782639swapJ = 212314782639no swapJ = 312318472639swapJ = 412318264739swapJ = 512318263947swapAfter each pass: passes 4 and 5 change nothingstart31124782639pass 1123182639474 swapspass 2128263139472 swapspass 3812263139471 swappass 4812263139470 swapspass 5812263139470 swapsAmber: the pair that was just swapped. Blue: guaranteed to be in its final place after that pass.
Pass 1: one comparison at a time12345631124782639J=112314782639swapJ=212314782639keepJ=312318472639swapJ=412318264739swapJ=512318263947swapAfter each pass: blue is guaranteed final12345631124782639startpass 1123182639474 swapspass 2128263139472 swapspass 3812263139471 swappass 4812263139470 swapspass 5812263139470 swapsAmber: the adjacent pair just swapped
Basic version: 5 passes of 5 comparisons
 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

1
Use a variable as the index, starting at the first element.
2
Compare the element at the index with the next element.
3
If it is greater, swap the two elements using a temporary variable.
4
Advance to the next adjacent pair, through J = 5; that completes this version's pass.
5
Repeat the passes until the whole array is in order.

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.

Pass 1, J = 1: one swap, line by line
The blue row of the table below.
LineStatement that runsJTempNums[J]Nums[J + 1]WritesWhat happens
3FOR J ← 1 TO 51J 1the first pair: elements 1 and 2
the first pair: elements 1 and 2
4IF Nums[J] > Nums[J + 1] THENtest 31 > 12 is true
test 31 > 12 is true
5Temp ← Nums[J]31Temp 31keep a copy of 31
keep a copy of 31
6Nums[J] ← Nums[J + 1]12Nums[J] 1212 moves into the first element; for a moment both hold 12
12 moves into the first element; for a moment both hold 12
7Nums[J + 1] ← Temp31Nums[J + 1] 31the copy in Temp goes into the second element
the copy in Temp goes into the second element
JPair comparedTempNums after this JWhat happens
J 1131, 123112 31 47 8 26 3931 > 12: swap them
31 > 12: swap them
J 2231, 4712 31 47 8 26 3931 > 47 is false: no swap
31 > 47 is false: no swap
J 3347, 84712 31 8 47 26 3947 > 8: swap them
47 > 8: swap them
J 4447, 264712 31 8 26 47 3947 > 26: swap them
47 > 26: swap them
J 5547, 394712 31 8 26 39 4747 > 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.

Your turn

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?

  1. 1
    14, 9, 20, 2, 17, 30: 30 has moved to the end
  2. 2
    4
  3. 3
    25: 5 passes × 5 comparisons, even when sorted early
Tick what you can do now
Exam focusCompare element 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.
Practise with s26/22 Q5(a), (c)(i); w21/21 Q2(a) (older paper: describe the sorting algorithm)
12 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Bubble sort: the improved algorithm

§10.2 · Arrays · an efficient bubble sort

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.

Improved version: flag and shrinking boundary
 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.

The sorting loop ends early; statements after that loop still run.

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.

Pass 4, line by line: the pass with no swaps
The blue row of the table below.
LineStatement that runsNoSwapsJBoundaryWritesWhat happens
5NoSwaps ← TRUETRUENoSwaps TRUEassume sorted until a swap happens
assume sorted until a swap happens
6FOR J ← 1 TO Boundary1J 1Boundary is 2
Boundary is 2
7IF Nums[J] > Nums[J + 1] THENtest 8 > 12 is false: no swap
test 8 > 12 is false: no swap
6FOR J ← 1 TO Boundary2J 2Boundary is 2
Boundary is 2
7IF Nums[J] > Nums[J + 1] THENtest 12 > 26 is false: no swap
test 12 > 26 is false: no swap
14Boundary ← Boundary - 11Boundary 1one fewer pair next time
one fewer pair next time
15UNTIL NoSwaps = TRUEtest NoSwaps = TRUE is true: the loop ends
test NoSwaps = TRUE is true: the loop ends
BoundaryComparesSwapsNoSwapsNums after the passWhat happens
start531 12 47 8 26 39line 3
line 3
pass 1454FALSE12 31 8 26 39 474 swaps: NoSwaps is FALSE, so repeat with one fewer comparison
4 swaps: NoSwaps is FALSE, so repeat with one fewer comparison
pass 2342FALSE12 8 26 31 39 472 swaps: NoSwaps is FALSE, so repeat with one fewer comparison
2 swaps: NoSwaps is FALSE, so repeat with one fewer comparison
pass 3231FALSE8 12 26 31 39 471 swap: NoSwaps is FALSE, so repeat with one fewer comparison
1 swap: NoSwaps is FALSE, so repeat with one fewer comparison
pass 4120TRUE8 12 26 31 39 47no 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

PassComparisonsSwapsNoSwaps at the endNums after the pass
154FALSE12 31 8 26 39 47
242FALSE12 8 26 31 39 47
331FALSE8 12 26 31 39 47
420TRUE8 12 26 31 39 47
Pass 4 makes no swaps, so the 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 valuesBasic comparisonsImproved passesImproved comparisons
31 12 47 8 26 39 as traced above25414
8 12 31 26 39 47 nearly sorted2529
8 12 26 31 39 47 already sorted2515

Basic: comparisons. Improved: passes and comparisons.

Six valuesBasicPassesCompared
31 12 47 8 26 39 as traced above25414
8 12 31 26 39 47 nearly sorted2529
8 12 26 31 39 47 already sorted2515
Your turn

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?

  1. 1
    2: pass 1 swaps 9 and 4; pass 2 makes no swaps
  2. 2
    3
  3. 3
    9 (5 + 4); the basic version makes 25
Tick what you can do now
Exam focusUse a conditional outer loop, the flag reset at the start of each pass and set when a swap happens, an inner loop over the right range, the comparison and the swap, and the boundary reduced after each pass.
Practise with s26/22 Q5(b)(i), (b)(ii)
13 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Sorting arrays with associated data

§10.2 · Arrays · bubble sort 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.

Before sortingNamesTimes1Lena52.42Raj48.93Tom55.14Ana47.35Kofi50.0Times swapped, names notNamesTimes1Lena47.32Raj48.93Tom50.04Ana52.45Kofi55.1Both arrays swappedNamesTimes1Ana47.32Raj48.93Kofi50.04Lena52.45Tom55.1Swapping only the times leaves 4 of the 5 names next to the wrong time. Swap the matching elements of both arrays together.
Before sortingIndexNamesTimes1Lena52.42Raj48.93Tom55.14Ana47.35Kofi50.0Times only: four wrong pairingsIndexNamesTimes1Lena47.32Raj48.93Tom50.04Ana52.45Kofi55.1Swap both: each pair stays togetherIndexNamesTimes1Ana47.32Raj48.93Kofi50.04Lena52.45Tom55.1

The same rule in three structures: wherever the data lives, everything that belongs together is swapped inside the same IF.

Parallel arrays: two swaps, two temporary variables
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
Array of records: one Temp record
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
2D array: swap every column of the row
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
A temporary variable must have the type of the value it holds: 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.
Your turn

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?

  1. 1
    Ana: the shortest time, 47.3, is first
  2. 2
    Kofi, 50.0
  3. 3
    Lena: the names never move, so the times no longer match them
Tick what you can do now
Exam focusSort by the field the question names and swap the matching elements in every array, or every column of the 2D row, inside the same IF. With an array of records a single swap moves the whole record.
Practise with s25/21 Q6(b); s26/22 Q5(c)(i), (c)(ii)
14 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Text files: storage, access modes and data types

§10.3 · Files · why files are needed

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.

Program, run 1array Names in RAMAshaBilalChenProgram, run 2array Names refilledAshaBilalChenNames.txtAshaBilalChensecondary storage: kept after the runWRITEFILEREADFILErun ends: RAM contents are lostno need to enter the data again
Program, run 1: Names in RAMAshaBilalChenProgram, run 2: Names refilledAshaBilalChenWRITEFILENames.txt · secondary storageAshaBilalChenOne string per lineKept after the runREADFILERun 1 ends; run 2 reads the saved lines.

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.

ModeUse it toData already in the file
READread lines with READFILE; test for the end with EOF()unchanged
WRITEcreate a new file, then write lines with WRITEFILElost: the file starts empty
APPENDadd lines after the existing data with WRITEFILEkept

One file, opened three times: follow which lines survive each mode, then check the output.

All three modes, one at a time
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"
Output
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 and STR_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.
Your turn

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?

  1. 1
    Closed: WRITE starts an empty file
  2. 2
    Started, Saved, Closed
  3. 3
    a text file holds only strings, so the number must be turned into text first
Tick what you can do now
Exam focusWhy use a file? The data is retained after the program ends (non-volatile), so it can be reused without being entered again. Name the mode: WRITE replaces the file, APPEND keeps what is there.
Practise with w25/21 Q4(b)(i), (b)(ii); w24/23 Q8(c)
15 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Reading a text file

§10.3 · Files · reading text files of one or more lines

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.

Read every line into the next element (at most 100 lines)
 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.txt
Asha
Bilal
Chen
Dara
Output
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.

Each pass reads the next line and stores it in the next element
Names.txtline 1Ashaline 2Bilalread in pass 2line 3Chenline 4DaraendEOF: TRUE
Names1Asha2BilalCount = 23Chen4Dara5unused100…
pass 2: line 2 read into Names[2]stored in another passnothing there
Pass 2, line by line
The blue row of the table below.
LineStatement that runsLineCountNames[Count]WritesWhat happens
6WHILE 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
7READFILE "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
8Count ← Count + 12Count 2the next element
the next element
9Names[Count] ← Line"Bilal"Names[Count] "Bilal"stored in Names[2]
stored in Names[2]
EOF("Names.txt")LineCountNames[Count]What happens
start0line 4; line 5 opens the file at its first line
line 4; line 5 opens the file at its first line
pass 1FALSE"Asha"1"Asha"line 1 of the file goes into Names[1]
line 1 of the file goes into Names[1]
pass 2FALSE"Bilal"2"Bilal"line 2 of the file goes into Names[2]
line 2 of the file goes into Names[2]
pass 3FALSE"Chen"3"Chen"line 3 of the file goes into Names[3]
line 3 of the file goes into Names[3]
pass 4FALSE"Dara"4"Dara"line 4 of the file goes into Names[4]
line 4 of the file goes into Names[4]
endTRUEno line left: the loop ends; CLOSEFILE, then output “4 names read”
no line left: the loop ends; CLOSEFILE, then output “4 names read”
Convert a numeric line with STR_TO_NUM() before using it
DECLARE 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.txt
8450
12030
10000
15210
7020
Output
Day 2: 12030
Day 4: 15210

Describe it in steps

  1. Open the file in read mode (close it after the loop).
  2. Set an index to 0.
  3. Until the end of the file, read a line into a string variable,
  4. 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 REPEAT loop would try to read a missing line.
  • EOF() never reads. To start again from line 1, close and reopen the file.
Your turn

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?

  1. 1
    Day 2: 10001; Day 4: 12000: 10000 is not more than 10000
  2. 2
    READFILE gives a STRING; the comparison with 10000 needs a number
  3. 3
    “0 names read”; the body runs 0 times because EOF is TRUE at the first test
Tick what you can do now
Exam focusOpen the file in READ mode once, before the loop; loop until EOF; read a line, use or store it, and move the index on inside the loop; close the file after the loop.
Practise with s24/23 Q2(a), (b); s25/23 Q4(a)
16 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Text files: writing and appending

§10.3 · Files · writing text files

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 separator
 1CONSTANT 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 program
R0417|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.

Index = 3, line by line: the line grows, then is written
The blue row of the table below.
LineStatement that runsLineTeam.txtWritesWhat happens
6Line ← Team[Index].RunnerID & Sep & Team[Index].Name"R0452|Ada Okoro"Line "R0452|Ada Okoro"ID, separator, name
ID, separator, name
7Line ← 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
8IF Team[Index].Paid THENtest Team[3].Paid is FALSE: false, so the ELSE branch runs
test Team[3].Paid is FALSE: false, so the ELSE branch runs
11Line ← 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
13WRITEFILE "Team.txt", Lineline 3Team.txt line 3one whole record per line
one whole record per line
IndexLine written to Team.txtWhat happens
Index 11"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 22"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 33"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"
File before
Omar
Priya
File after
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.

Your turn

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. 1
    R0388|Tomas Ruiz|19.5|N
  2. 2
    Lena, Raj, Tom: WRITE started an empty file, so Omar and Priya are lost
  3. 3
    5: the 2 already there and 3 new ones; empty strings are skipped
Tick what you can do now
Exam focusEvery value written must be a string: convert numbers with 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.
Practise with w25/23 Q2(a); w24/22 Q8(b), (c); w25/23 Q8(c)(ii), (c)(iii)
17 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Restoring records and searching a text file

§10.3 · Files · fields, conversion and search

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.

One saved line becomes one typed record
LineR0417|Mei Lin|21.75|Ya STRING
Extractfield 1R0417STRINGfield 2Mei LinSTRINGfield 321.75STRINGfield 4YSTRING
Team[1].RunnerIDR0417STRING.NameMei LinSTRING.BestTime21.75REAL: STR_TO_NUM.PaidTRUEBOOLEAN: = "Y"
text taken from the linestored with 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.

Restore the three saved runner records
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"
Find the first matching line; stop reading early
 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.

Names.txt, searched for CHEN: each line is read, then compared in lower case
Names.txtline 1Ashano matchline 2Bilalno matchline 3Chenmatch: FoundAt = 3line 4Daranever read
read: no matchread: the first matchnot read: the loop has ended
LineTO_LOWER(Line)PositionFoundAtWhat happens
start0−1lines 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"33"chen" = "chen": FoundAt ← 3
"chen" = "chen": FoundAt ← 3
endFoundAt 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

First line of Team.txt
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
Prepare a line counter and an absent-result value, then open the saved names for reading.
2
While there is another line and no match yet, read one name, advance the counter and compare both names in the same case.
3
On a match, save that line number. Once the search ends, close the file and report the saved number or the absent result.
Your turn

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?

  1. 1
    4: the case is ignored
  2. 2
    -1; all 4 lines are read before EOF ends the loop
  3. 3
    convert it with STR_TO_NUM(): every field extracted from a line is a STRING, and BestTime is REAL
Tick what you can do now
Practise with w24/23 Q8(b); s26/22 Q3
18 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Abstract data types

§10.4 · Introduction to ADTs · stack, queue and linked list

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.

Stack: last in, first outPQRSToppushpopadded and removed at the topQueue: first in, first outJ1J2J3J4dequeueenqueueFrontRearadded at the rear, removed from the frontLinked list: order set by pointersStartDateFigLimeØnode = data + pointer to the next nodeØ: null pointer, the end of the listinsert or delete by changing pointers
Stack · last in, first outPQRSpoppushTopQueue · first in, first outJ1J2J3J4dequeue at Frontenqueue at RearFrontRearLinked list · follow pointersStartDate•Fig•Lime0Each node: data + next pointer; 0 ends the list

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.

ADTKey featuresJustify it when…
StackLast 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
QueueFirst 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 listEach 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

1
Jobs J1, J2 and J3 arrive in that order: add each at the rear.
2
Remove from the front: J1 leaves first, then J2, then J3.
3
FIFO preserves arrival order, so a later job cannot overtake an earlier job.

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.
Your turn

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?

  1. 1
    a queue: first in, first out keeps arrival order
  2. 2
    a stack: last in, first out gives the newest change first
  3. 3
    a linked list: a new node is linked into place by changing pointers; no data is moved
Tick what you can do now
Exam focusA feature answer names the rule (LIFO or FIFO) and the pointers used. Saying the structure “uses an array” describes how it might be built, not a feature of the ADT. Link every justification to the situation in the question.
Practise with s25/23 Q2(c); s26/22 Q4(b); s26/21 Q7(a)(i), (a)(ii)
19 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

A stack in an array

§10.4 · ADTs · stack: push and pop

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.

Initial876543N2W1TTopTop = 3Group 1PUSH 'G', PUSH 'K'8765K4G3N2W1TTopTop = 5Group 2POP, POP, POP8765(K)4(G)3(N)2W1TTopTop = 2popped K, G, NGroup 3PUSH 'R', POP, PUSH 'S'8765(K)4(G)3S2W1TTopTop = 3popped R
Initial876543N2W1TTop = 3Brackets: outside the stackGroup 1PUSH 'G', PUSH 'K'8765K4G3N2W1TTop = 5Brackets: outside the stackGroup 2POP, POP, POP8765(K)4(G)3(N)2W1TTop = 2popped: K, G, NBrackets: outside the stackGroup 3PUSH 'R', POP, PUSH 'S'8765(K)4(G)3S2W1TTop = 3popped: RBrackets: outside the stack

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

1
Check the stack is not full: if Top = 8, report an error and stop.
2
Increment Top.
3
Store the item in Stack[Top].

POP an item

1
Check the stack is not empty: if Top = 0, report an error and stop.
2
Copy the item from Stack[Top].
3
Decrement 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 designEmptyFullPush
Top: last item added08add 1, store
SP: next free element19store, 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.

Your turn

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. 1
    'Y'
  2. 2
    Top = 4; Stack[5] still holds 'Y', but it is above Top, so it is not on the stack
  3. 3
    report that the stack is full and stop: Top = 8 is the upper bound
Tick what you can do now
Exam focusShow the pointer and the data after every group. The value that has been on the stack longest is at the bottom. Before a push check full, before a pop check empty.
Practise with s25/23 Q2(a)(ii); w24/22 Q3(a)(ii)
20 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

A circular queue in an array

§10.4 · ADTs · queue: add and remove

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.

Initial123J14J25J36J4FrontRear6 → 1NumItems = 4Step 1ENQUEUE J51J523J14J25J36J4FrontRear6 → 1NumItems = 5Step 2DEQUEUE ×21J523(J1)4(J2)5J36J4FrontRear6 → 1NumItems = 3removed J1, J2Step 3ENQUEUE J6, J71J52J63J74(J2)5J36J4FrontRear6 → 1NumItems = 5Step 4ENQUEUE J8, J91J52J63J74J85J36J4FrontRear6 → 1NumItems = 6J9 refused: full
Initial123J14J25J36J4FrontRear6 → 1NumItems = 4Read from Front; wrap 6 → 1.ENQUEUE J5ENQUEUE J51J523J14J25J36J4FrontRear6 → 1NumItems = 5Read from Front; wrap 6 → 1.DEQUEUE ×2DEQUEUE ×21J523(J1)4(J2)5J36J4FrontRear6 → 1NumItems = 3removed J1, J2ENQUEUE J6, J7ENQUEUE J6, J71J52J63J74(J2)5J36J4FrontRear6 → 1NumItems = 5Read from Front; wrap 6 → 1.ENQUEUE J8, J9ENQUEUE J8, J91J52J63J74J85J36J4FrontRear6 → 1NumItems = 6J9 refused: full

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 and initialise an empty queue
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.

StepENQUEUE: add an itemDEQUEUE: remove an item
1if NumItems = 6 the queue is full: stopif NumItems = 0 the queue is empty: stop
2add 1 to Rear; if it passes 6, set it to 1 (wrap around)copy the item from Queue[Front]
3store the item in Queue[Rear]; add 1 to NumItemsadd 1 to Front (wrap around); subtract 1 from NumItems

Two ways to design Rear

Rear holds the index ofAdd an itemRear after step 3
the last item added (as in the steps)add 1 to Rear (wrap), then store3
the next free elementstore, 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 = Rear means one item.
  • A different design uses a next-free Rear and reserves one element: empty when Front = Rear, full when advancing Rear would reach Front. It holds at most five items.
Your turn

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?

  1. 1
    J3, J4: the front items
  2. 2
    1: 6 wraps round to 1
  3. 3
    element 5, freed when J3 was removed; NumItems = 5
Tick what you can do now
Exam focusAdding: check full, increment the end pointer and wrap around, then store the item. Removing: check empty, take the item at the front pointer, then move it on. Describe the pointer and the data.
Practise with s26/21 Q7(b)(i), (b)(ii), (b)(iii)
21 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Linked lists in arrays

§10.4 · ADTs · linked list: nodes, pointers and the free list

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.

The list in order, and the free list (node index above each node)StartDate[4]Fig[2]Lime[3]Plum[1]ØFree[5][6][7]Øunused nodes, ready to be takenAfter initialisation: an empty listIndexDataPointer12233445566770Start0Free1After adding Plum, Fig, Lime, DateIndexDataPointer1Plum02Fig33Lime14Date2566770Start4Free5Start = 0: null,the list is empty.Free = 1: everynode is on thefree list.Data stays where it wasstored: Plum is in 1.The pointers give theorder: 4 → 2 → 3 → 1 → 0.
Start: 4 → 2 → 3 → 1 → 0Date, Fig, Lime, PlumFree: 5 → 6 → 7 → 0After initialisation: all nodes freeStart = 0 · Free = 1IndexDataPointer12233445566770After Plum, Fig, Lime, DateStart = 4 · Free = 5IndexDataPointer1Plum02Fig33Lime14Date2566770

Traverse the list

1
Set Current to the start pointer.
2
While Current is not the null pointer (0), repeat steps 3 and 4.
3
Output Data[Current].
4
Set Current to Pointer[Current].

Here Current takes the values 4 → 2 → 3 → 1 → 0 and the output is Date, Fig, Lime, Plum.

Initialise: an empty list, every node free
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: Data for the items and Pointer (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.
The list's logical length can change, but these arrays have capacity 7. When Free = 0, no unused node remains.
Your turn

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?

  1. 1
    4 → 2 → 3 → 1, then 0
  2. 2
    node 5: Free points to it
  3. 3
    0: node 1 (Plum) is the last node of the list
Tick what you can do now
Exam focusFollow the pointers from the start pointer, not the index order. The null pointer means there are no further nodes. After initialisation the start pointer is null and every node is on the free list.
Practise with s24/21 Q3(a), (b); w24/23 Q3(a)(i), (c); s25/23 Q2(b)(i); s26/23 Q6(a), (b)
22 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Linked lists: insert and delete

§10.4 · ADTs · linked list: add, edit and delete data

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.

Return node 3 to Free; its old data remains.IndexDataNext1Plum02Fig53Lime64Date25Kiwi16—77—0Start = 4Follow Next:[4] Date[2] Fig[5] Kiwi[1] PlumFree = 33 → 6 → 7 → 0Changed linksinsert: 5 → 3, then 2 → 5delete: 5 → 1; node 3 becomes FreeArray locations stay fixed.Lime remains in Data[3], inactive.
Return node 3 to Free; its old data remains.IndexDataNext1Plum02Fig53Lime64Date25Kiwi16—77—0Start = 4Follow Next:[4] Date[2] Fig[5] Kiwi[1] PlumFree = 33 → 6 → 7 → 0Fixed storage: existing data never shifts.After deletion, node 3 still stores Lime.Only its membership and links change.

Insert Kiwi in order

1
Check there is a free node: Free = 5.
2
Store Kiwi in Data[5]; Free ← Pointer[5] = 6.
3
From Start, follow the pointers, keeping the previous node, until a node holds a later item: previous = 2 (Fig), current = 3 (Lime).
4
Pointer[5] ← 3: Kiwi points to Lime.
5
Pointer[2] ← 5: Fig points to Kiwi.

Delete Lime

1
From Start, follow the pointers, keeping the previous node, until Lime is found: previous = 5 (Kiwi), current = 3.
2
Pointer[5] ← Pointer[3] = 1: Kiwi now points to Plum, bypassing Lime.
3
Return node 3 to the free list: 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.

Your turn

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?

  1. 1
    node 3: the first free node, where Lime’s old data still sits
  2. 2
    the start pointer: Start ← 3, and Pointer[3] ← 4 (Date)
  3. 3
    6
Tick what you can do now
Practise with s26/23 Q6(c)(i), (c)(ii), (d); s25/22 Q6(b)
23 / 24
9618 · Unit 10 · Data types and structures
Revisionbyexamplicity

Stacks and queues: applications and data order

§10.4 · ADTs · using a stack and a queue together

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.

StartstackPQRSTopqueueemptyPop each item, add it to the queuestackemptyqueueSRQPFrontRearRemove each item, push it backstackSRQPTopqueueemptyBottom to top the stack held P Q R S; now it holds S R Q P, so P is on top.
StartstackPQRSTopqueueemptyPop each item, add it to the queuestackemptyqueueSRQPFrontRearRemove each item, push it backstackSRQPTopqueueempty

Reverse a stack using a queue

1
Pop an item and update the top-of-stack pointer; add it at the rear of the queue and update the rear pointer.
2
Repeat until the stack is empty.
3
Remove the front item from the queue and update the front pointer; push it onto the stack and update the top-of-stack pointer.
4
Repeat until the queue is empty.

Save a stack to a text file

1
Open the file in WRITE mode.
2
Check that there is an item on the stack.
3
Pop the item and write it to the file as a line.
4
Repeat from step 2; then close the 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 stackShownForward stackWhat happens
starthome newssportemptythree pages visited; Back holds the earlier two
three pages visited; Back holds the earlier two
BackhomenewssportBack: push sport onto Forward, pop news from Back
Back: push sport onto Forward, pop news from Back
Backemptyhomesport newsBack: push news onto Forward, pop home from Back
Back: push news onto Forward, pop home from Back
ForwardhomenewssportForward: 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.

ClickBack stackShownForward
starthome newssportempty
Backhomenewssport
Backemptyhomesport news
Forwardhomenewssport

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.

Your turn

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?

  1. 1
    C, B, A: the top item first
  2. 2
    C, B, A: a queue keeps the order it was given
  3. 3
    a stack: the last item in is the first out
Tick what you can do now
Exam focusFor a multi-step ADT task, give every operation in order, the pointer update after each one and the condition that ends each loop (stack empty, queue empty).
Practise with s25/21 Q5; s26/22 Q4(a); s23/23 Q3(b)(ii) (older paper: save the stack to a file)
24 / 24