Skip to content

9618 · Unit 13 · Paper 3: Advanced theory

User-defined types and file organisation.

9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

User-defined types

§13.1 · User-defined types

INTEGER holds a number and STRING holds text, but a lantern in a hire shop is an ID, a wattage and a status all at once. A user-defined type lets the programmer design a type for data like that, then declare variables of that type.

One lantern, three fields, each with its own type:

LanternRecordIDINTEGERWattageINTEGERStatusLanternStatusOne value: 31 · 6 · AvailableRelated fields travel together

Build the type the application needs

Tavren, a lantern hire shop, needs a count, a status with exactly three values, and each lantern’s ID, wattage and status kept together. A record groups related fields like those under one identifier; INTEGER alone cannot express the combination.

NeedType choiceWhy it fits
A count of lanternsBuilt-in INTEGERThe language already supplies whole-number values and arithmetic.
Exactly three named statesEnumerated LanternStatusThe definition lists the complete allowed values.
One lantern’s related detailsComposite LanternRecordEach named field has its own suitable type.

A type definition is reusable

  • Define LanternRecord once, then use it for one lantern, an array element or a file record.
  • The name describes the data and makes declarations easier to read.
  • A type definition describes the values a variable may hold; a declaration creates the variable.
Non-composite types here include enumerated and pointer types. Composite types include sets, records and classes/objects: they combine data components.
Your turn

1 A lantern’s colour must be one of Red, Amber or Green. Which kind of type fits?

2 A program keeps a customer’s name, phone number and number of hires together. Which kind of type fits?

3 What is the difference between a type definition and a declaration?

  1. 1
    an enumerated type: it lists the complete set of allowed values
  2. 2
    a record (composite) type: related fields of different types under one identifier
  3. 3
    a type definition describes the values; a declaration creates a variable of that type
Tick what you can do now
Practise with s26/33 Q1(a); s26/31 Q1(a)
1 / 9
9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

Enumerated and pointer types

§13.1 · User-defined types

A lantern is available, on loan or in repair, and never anything else. An enumerated type restricts a value to a fixed list like that. Sometimes a program needs to say where a value is kept rather than what it is: a pointer type stores a reference to a memory location holding a value of a specified type.

Enumerated type · declaration syntax
TYPE LanternStatus = (Available, OnLoan, Repair)
DECLARE CurrentStatus : LanternStatus
  • CurrentStatus ← Available selects one listed value.
  • The values are unique, the list is complete and their order is fixed by the declaration.
  • Available is an enumerated value, not the string "Available": the declaration has no quotation marks around it.

A pointer answers a different question: not what a value is, but where it is kept.

Pointer type · declaration syntax
TYPE WattRef = ^INTEGER
DECLARE WattPointer : WattRef

Follow the arrow: the pointer holds an address, and the box at that address holds the value.

WattPointeraddress 420Wattage6location 420WattPointer^ reads the value 6

Address and value are different

  1. 1
    If Wattage is an INTEGER with value 6, WattPointer ← ^Wattage stores its address: the leading caret obtains the address.
  2. 2
    WattPointer^ uses a trailing caret to dereference it and read 6.
  3. 3
    If Wattage becomes 9 at the same location, dereferencing now reads 9.
ExpressionMeaning
WattPointerReference to location 420 in this memory picture.
WattPointer^The INTEGER value stored at that location.
CurrentStatusOne of Available, OnLoan or Repair; no address is involved.
Your turn

1 TYPE Day = (Mon, Tue, Wed). Is "Mon", with quotation marks, a value of type Day?

2 WattPointer holds address 420 and location 420 now stores 12. What does WattPointer^ give?

3 In the same memory, what does WattPointer itself hold?

  1. 1
    no: Mon is an enumerated value; "Mon" is a string
  2. 2
    12, the value at the location
  3. 3
    420, the address
Tick what you can do now
Practise with s26/32 Q1(a), Q1(b); s26/31 Q1(b)
2 / 9
9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

Sets, records and objects

§13.1 · User-defined types

Two counters each pick out some lanterns. To ask which lanterns both chose, you need a type that records which lanterns belong, not their order. Choose the structure by what one value must represent: membership, related fields, or state with operations.

A set stores each member once

Set type and values · declaration syntax
TYPE LanternIDs = SET OF INTEGER
DEFINE CounterA (31, 8, 22) : LanternIDs
DEFINE CounterB (8, 14) : LanternIDs

Draw the two sets as circles: an ID in the overlap was picked at both counters.

CounterACounterB2231148in both

Read each operation off the circles:

Set operationResultMeaning at the counters
Intersection A ∩ B{8}ID 8 appears in both selections.
Union A ∪ B{8, 14, 22, 31}Every selected ID, once each.
22 ∈ ATRUEMembership: ID 22 is in CounterA.
  • All members have the declared element type.
  • A set is unordered and has no duplicates: adding 8 again to A leaves three members. There is no “second member” to retrieve by position.
  • Members may be added or removed; an enumeration instead defines its complete list of possible values.

An object holds state and offers methods

A record only holds data. A lantern can also be hired, and an object keeps that action with the data it changes.

Python
class Lantern:
def __init__(self, ID):
self.ID = ID
self.Status = "available"
def Hire(self):
if self.Status == "available":
self.Status = "on-loan"
a = Lantern(31)
b = Lantern(8)
a.Hire()
print(a.Status, b.Status)

The program makes two objects from one class, then hires only a:

class Lanternattributes ID, Status · method Hire()object aID 31Status on-loanobject bID 8Status available

The class defines attributes and methods. Objects a and b are separate instances. Hiring a changes only its state. A record groups fields; use a class when the state and its permitted operations belong together.

Your turn

1 CounterC holds 8 and 19. Give CounterA ∩ CounterC.

2 Give CounterA ∪ CounterC.

3 After the program above, b.Hire() also runs. What does print(a.Status, b.Status) show now?

  1. 1
    {8}
  2. 2
    {8, 19, 22, 31}
  3. 3
    on-loan on-loan
Tick what you can do now
Practise with s26/31 Q1(a); s26/32 Q11(b) (instance term); w24/31 Q6(a–b) (older paper: sets)
3 / 9
9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

Designing a record type

§13.1 · User-defined types

A wattage of 7 or a status of “lost” would break the program later, so start from what each field means and which values are valid. Then define the record type, declare a record variable and assign every field before using it.

For stored Tavren records, ID is a whole-number identifier, Wattage is 6, 9 or 12, and Status is the text available, on-loan or repair. The text form makes the file format explicit; a runtime model may instead use LanternStatus for that field.

Pseudocode
TYPE LanternRecord
DECLARE ID : INTEGER
DECLARE Wattage : INTEGER
DECLARE Status : STRING
ENDTYPE
DECLARE Item, Copy : LanternRecord
DECLARE Stock : ARRAY[0:5] OF LanternRecord
Item.ID ← 31
Item.Wattage ← 6
Item.Status ← "available"
Copy ← Item
Copy.Status ← "on-loan"
Stock[0] ← Item
OUTPUT Stock[0].ID, " ", Stock[0].Status
OUTPUT Copy.ID, " ", Copy.Status

Copy a record and select its fields

Follow the program to its end: three record variables, and only one field differs.

ItemID31Wattage6StatusavailableCopyID31Wattage6Statuson-loanStock[0]ID31Wattage6StatusavailableBlue: the only field that changed after Copy ← Item

Each statement, and what it does to those records:

OperationResult
Copy ← ItemAll three fields are copied as one LanternRecord value.
Copy.Status ← "on-loan"Only Copy changes; Item remains available.
Stock[0].IDSelect record 0, then its ID field: 31.
  • The record has a fixed set of related fields, which may have different types.
  • An array of records stores many complete lantern values.
  • A file key identifies a record for this application; a field’s name or position alone does not make its values unique.
Your turn

1 Write the statement that sets the Wattage of Stock[2] to 9.

2 After the program above, Item.Wattage ← 12 runs. What is Copy.Wattage?

3 In Stock[0].ID, what does Stock[0] select, and what does .ID select?

  1. 1
    Stock[2].Wattage ← 9
  2. 2
    6: Copy holds its own copy of the fields
  3. 3
    Stock[0] selects one record in the array; .ID selects one field of that record
Tick what you can do now
Practise with w24/32 Q3(a–b); w25/31 Q1(a) (older papers: record declaration and use)
4 / 9
9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

Serial and sequential files

§13.2 · File organisation and access

A file is only useful if the program can find a record in it again. Two choices decide how. File organisation describes how records are arranged; file access describes how a program reaches them. Keep them apart: the stored order is not the reading method.

The same six lanterns stored two ways. Follow the arrows: that is the order a program reads them.

Serial: arrival order31142782219Sequential: ID order81419222731

What sets each order, and where Tavren uses it:

OrganisationStored orderTavren use
SerialNew records are appended in arrival/time order. There is no ID ordering.A log of lanterns received at a counter.
SequentialRecords are stored in a stated order using a key field; here, ascending ID.An ID-ordered stock list for a complete daily check.

Sequential access reads one record after another

Order pays off when you search. Follow each search one record at a time, and be able to say when it stops.

Serial file: search for 8
RecordTest
read 131not 8: read on
not 8: read on
read 214not 8: read on
not 8: read on
read 327not 8: read on
not 8: read on
read 488: stop, found
8: stop, found
Sequential file: search for 20
RecordTest
read 188 is below 20: read on
8 is below 20: read on
read 21414 is below 20: read on
14 is below 20: read on
read 31919 is below 20: read on
19 is below 20: read on
read 42222 is past 20: stop, absent
22 is past 20: stop, absent
  • A serial search stops at a matching key, or at end of file if the key is absent.
  • A sequential search can stop early: once a key is past the target, the target cannot occur later. A search for 8 stops at the first record.

Serial search for 8: read 31 → 14 → 27 → 8: four records. Stop at a matching key, or at end of file if absent.

Sequential search for 20: read 8 → 14 → 19 → 22. Since 22 exceeds 20 in this ascending file, stop: 20 cannot occur later. A search for 8 stops at the first record.

Insertion must preserve the chosen order

  1. 1
    A new ID 25 goes at the end of the serial log.
  2. 2
    In the ID-ordered sequential file it belongs between 22 and 27: copy records to a new file, insert 25 at that point, then copy the remaining records.
  3. 3
    Appending alone would break key order.
Your turn

1 In the serial log 31, 14, 27, 8, 22, 19, how many records are read to find 22?

2 In the sequential file, a search for 25 stops at which record? How many records are read?

3 Where does a new ID 10 go in each file?

  1. 1
    5
  2. 2
    at 27, which is past 25: 5 records read
  3. 3
    serial: at the end; sequential: between 8 and 14
Tick what you can do now
Practise with s26/33 Q3; s26/32 Q4
5 / 9
9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

Random organisation and direct access

§13.2 · File organisation and access

Reading every record to find one lantern is slow when a customer is waiting at the counter. Direct access uses a record’s location to reach it without first scanning all preceding records. Random organisation places records using a location derived from the record key.

Follow lantern 8: the hash points to slot 2, then the search moves on until the IDs match.

Record keyFirst slot88 MOD 6 = 2ID 19Slot 0ID 31Slot 1ID 14≠ 8Slot 2ID 27≠ 8Slot 3ID 8matchSlot 4ID 22Slot 5Probe234Stop
  1. 1
    Tavren uses six numbered record slots, 0–5.
  2. 2
    The hash ID MOD 6 gives the first slot to check. Records are not stored in ID or arrival order.
  3. 3
    When keys share a slot, a collision rule decides where the later record goes.

A key, a position and an index all look like numbers, but each does a different job:

IdentifierExampleJob
Record keyID 8Identifies the required lantern.
Record positionSlot 4Locates its stored record after collision handling.
Array indexStock[4]Selects an element in memory; it is not automatically a file address.

A sequential file can also provide direct access

Sometimes the file must stay in ID order for the daily check, yet hires still need a quick lookup.

IndexSequential filekeypositionpositionrecord800ID 81411ID 141922ID 192233ID 222744ID 273155ID 31
  1. 1
    Keep the ID-ordered file and build an index mapping each key to its record location.
  2. 2
    Search the index: key 22 maps to position 3. Retrieve position 3 and read the record directly.
  3. 3
    The file remains sequentially organised even though this access does not scan it.
A record position counts records from the file’s beginning in this model. A real byte address also depends on record size and the file’s address convention. Random access does not mean selecting records by chance.
Your turn

1 Which slot does ID 25 hash to first with ID MOD 6?

2 Using the index above, which position holds ID 27?

3 Does random organisation mean records are placed by chance?

  1. 1
    25 MOD 6 = 1
  2. 2
    position 4
  3. 3
    no: each location is worked out from the record key
Tick what you can do now
Practise with s26/31 Q2; s24/32 Q7 (older paper: indexed sequential access)
6 / 9
9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

Hashing algorithms

§13.2 · File organisation and access

To store a record by its key, you need a rule that turns the key into a place. A hashing algorithm transforms a key into a location in a bounded address space. Use the same rule to store a record and to find it, and you always look in the right place first.

Numeric keys: use the remainder

For Tavren’s six slots, use h(ID) = ID MOD 6. MOD gives a remainder from 0 to 5, so every result is a valid slot.

IDID MOD 6First slot31142782219slot 0slot 1: collisionslot 2: collisionslot 3slot 4slot 5

The division behind each line of the figure:

IDCalculationFirst slot
3131 = 5 × 6 + 11
1414 = 2 × 6 + 22
2727 = 4 × 6 + 33
88 = 1 × 6 + 22
2222 = 3 × 6 + 44
1919 = 3 × 6 + 11

IDs 14 and 8 both produce 2, and 31 and 19 both produce 1. Each is a collision: different keys share an initial address. It does not mean the records have the same identity.

Character keys: combine character codes, then reduce

Some keys are text, not numbers. For a text ID such as L31, add the ASCII character codes and take MOD 6. This is a different key-to-number procedure; the resulting address still needs collision handling.

L31: 76 + 51 + 49 = 176; 176 MOD 6 = 2Character codes are summed before applying the modulus.L14: 76 + 49 + 52 = 177; 177 MOD 6 = 3A different key may produce a different slot.L13: 76 + 49 + 51 = 176; 176 MOD 6 = 2Reordering these characters leaves the sum unchanged: another collision.
  • A useful hash spreads the expected keys across the available slots; a poor spread creates long searches.
  • More slots or a better distribution can reduce collisions. A defined resolution method is still needed.
Your turn

1 Find the first slot for ID 40 with ID MOD 6.

2 Which two of IDs 13, 20 and 26 collide?

3 Find the first slot for the text key L22 (L = 76, 2 = 50).

  1. 1
    40 = 6 × 6 + 4: slot 4
  2. 2
    20 and 26: both give 2 (13 gives 1)
  3. 3
    76 + 50 + 50 = 176; 176 MOD 6 = 2
Tick what you can do now
Practise with s26/31 Q2(b–c); w25/41 Q3(c) (older paper: numeric hash)
7 / 9
9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

Hash collisions and record retrieval

§13.2 · File organisation and access

Two lanterns can hash to the same slot, and only one record fits there. Linear probing checks consecutive slots after a collision, wrapping from the last slot to the first. Insertion and lookup must follow the same probe sequence, or a stored record is never found.

Tavren’s six lantern IDs collide twice under ID MOD 6. Insert 31, 14, 27, 8, 22, 19, in that arrival order. All slots are initially empty; each stored record keeps its full ID.

One row per insertion: each ID is written in the slot where it ends up.

Slot 0Slot 1Slot 2Slot 3Slot 4Slot 5What happens
insert 313131 MOD 6 = 1: slot 1 is empty, store here
31 MOD 6 = 1: slot 1 is empty, store here
insert 141414 MOD 6 = 2: slot 2 is empty, store here
14 MOD 6 = 2: slot 2 is empty, store here
insert 272727 MOD 6 = 3: slot 3 is empty, store here
27 MOD 6 = 3: slot 3 is empty, store here
insert 888 MOD 6 = 2: slots 2, 3 taken; store in slot 4
8 MOD 6 = 2: slots 2, 3 taken; store in slot 4
insert 222222 MOD 6 = 4: slot 4 taken; store in slot 5
22 MOD 6 = 4: slot 4 taken; store in slot 5
insert 191919 MOD 6 = 1: slots 1, 2, 3, 4, 5 taken, wrap to 0; store in slot 0
19 MOD 6 = 1: slots 1, 2, 3, 4, 5 taken, wrap to 0; store in slot 0
end19311427822every slot is full
every slot is full

The last insertion, slot by slot: 19 finds five slots taken and wraps round to slot 0.

Insert 19: 19 MOD 6 = 1ID 19storedSlot 0ID 31takenSlot 1ID 14takenSlot 2ID 27takenSlot 3ID 8takenSlot 4ID 22takenSlot 5123456After the last slot, wrap round to slot 0
IDHashSlots checkedStored at
31111
14222
27333
822 → 3 → 44
2244 → 55
1911 → 2 → 3 → 4 → 5 → 00
Slot012345
ID19311427822

Find ID 8 by comparing the stored keys

1
Calculate 8 MOD 6 = 2 and read slot 2: its ID is 14, so this is not the target.
2
Probe slot 3: ID 27 is also different. Probe slot 4: ID 8 matches.
3
Return the whole record from slot 4. Update its status there if needed; do not overwrite the record at the original hash slot.

When to stop searching for a missing key

A search for a key that is not there must still end somewhere.

  1. 1
    ID 20 hashes to 2 and checks 2 → 3 → 4 → 5 → 0 → 1. After all six slots, it is absent.
  2. 2
    In a partly filled table with no deletions, reaching a never-used empty slot also proves absence.
  3. 3
    Insertion into this full table must report full rather than overwrite a different key.
  • Other schemes use a separate overflow area or a linked chain for keys with the same hash.
  • Store and search using that scheme’s rule: a hash alone does not identify the final location after a collision.
Your turn

1 In the full table, which slots does a search for ID 27 check?

2 List the slots a search for ID 25 checks. What is the result?

3 An empty six-slot table gets IDs 12, 18 and 24, in that order. Where is each stored?

  1. 1
    slot 3 only: it matches first time
  2. 2
    1 → 2 → 3 → 4 → 5 → 0: all six slots checked, so 25 is absent
  3. 3
    12 in slot 0; 18 collides and goes to slot 1; 24 collides twice and goes to slot 2
Tick what you can do now
Practise with s26/31 Q2(c); w25/41 Q3(d), Q3(f) (older paper: bucket-based coding variant)
8 / 9
9618 · Unit 13 · User-defined types and file organisation
Revisionbyexamplicity

Choosing organisation and access

§13.2 · File organisation and access

No file suits every job: one task must preserve arrival history, another process records in key order, another retrieve and update individual records quickly. Choose from the workload, and state both the organisation and the access method.

Four Tavren jobs, each matched to a file. Read each row from the job to the reason it suits.

Tavren requirementOrganisation and accessReason
Record each lantern’s arrival at a counterSerial file; append, then sequential accessAppending preserves the arrival sequence with no sorting step.
Check every lantern in ascending ID orderSequential file; sequential accessOne pass visits every record in the required order.
Look up one known ID during a hireRandom file; direct access using a hashThe ID leads to a location, then collision checks, avoiding a full scan in the usual case.
Keep an ordered list and support individual lookupsSequential file with an index; direct accessThe index supplies the record address while the file retains key order.

Update one record in each kind of file

Files are changed as well as read. When lantern 8 is hired, its status goes from available to on-loan and its ID stays 8. Each kind of file makes that change differently.

Random file: change slot 4 in placeID 19Slot 0ID 31Slot 1ID 14Slot 2ID 27Slot 3ID 8on-loanSlot 4ID 22Slot 5read, change, write backSequential file: copy every record to a new file88on-loan14141919222227273131
  1. 1
    Random file: find slot 4 through the hash and probing rule, read the record, change Status and write it back to slot 4. Other records stay in place.
  2. 2
    Simple sequential file: read each old record and write a new file, replacing the matching record’s status and copying every other record unchanged. This preserves ID order.
  3. 3
    Indexed fixed-record file: a direct update at the indexed location.

What each method costs

Speed at the counter is not free.

  • Random access needs an address rule, collision handling and spare capacity.
  • An index needs storage, and maintenance when record locations change.
  • Sequential scanning suits a task that already needs every record; a direct lookup suits a task that needs one known key.
Your turn

1 Every night, a library prints all members’ records in membership-number order. Which organisation and access fit?

2 A help desk looks up one customer by ID while they wait. Which organisation and access fit?

3 Why does a simple sequential file write a new file to change one record?

  1. 1
    sequential file, sequential access: every record is needed, in key order
  2. 2
    random file with direct access by hashing the ID: one known key, found quickly
  3. 3
    the records are copied in order into the new file, so the key order is kept while one record changes
Tick what you can do now
Practise with s26/31 Q2; s26/32 Q4; s26/33 Q3; s24/32 Q7 (older paper: access comparison)
9 / 9