Cambridge IAS-Level · thinka-original Practice Paper

2026 Cambridge IAS-Level Computer Science (9618) Practice Paper with Answers

Thinka Jun 2026 (V2) Cambridge International AS Level-Style Mock — Computer Science (9618)

150 marks210 mins2026
An original Thinka practice paper modelled on the structure and difficulty of the Jun 2026 (V2) Cambridge International AS Level Computer Science (9618) paper. Not affiliated with or reproduced from Cambridge.

Paper 1 Theory Fundamentals

Answer all questions. Calculators must not be used. Write answers clearly in the spaces provided.
18 Question · 54 marks
Question 1 · short-answer
2.5 marks
A digital graphic designer is creating icons for a mobile operating system.

Define the term colour depth in the context of bitmap images, and describe the effect that increasing colour depth has on the image representation and file storage requirements.
Show answer & marking scheme

Worked solution

1. Definition: Colour depth is the number of bits used to encode the colour value of a single pixel in a bitmap graphic (calculated as \(2^n\) possible colours for an \(n\)-bit depth).
2. Effect on image: A higher colour depth increases the range/palette of possible colours, allowing smoother gradients, better photorealism, and reducing colour banding.
3. Effect on storage: Each pixel requires more bits of data, which directly increases the total file size and memory requirements.

Marking scheme

1 mark (MP1): Defining colour depth as the number of bits used/allocated per pixel to represent colour.
1 mark (MP2): Stating that increasing colour depth increases the range/number of available colours (or improves image quality/colour accuracy/reduces banding).
0.5 marks (MP3): Stating that increasing colour depth increases the resulting file size / storage demand.

[Guidance: Reject 'increases resolution' for MP2. Reject vague references to 'makes image bigger' without clear reference to file size/bytes for MP3.]
Question 2 · short-answer
2.5 marks
An enterprise local area network (LAN) uses IPv4 addressing across multiple departments.

Explain the purpose of a subnet mask in an IPv4 network, and describe how it is used by a host device to determine whether a destination IP address is on the local network.
Show answer & marking scheme

Worked solution

1. Purpose: A subnet mask defines the boundary between the network ID portion and the host ID portion of a 32-bit IPv4 address.
2. Mechanism: The sending device performs a bitwise logical AND between its own IP address and the subnet mask to find its local network address.
3. Decision: The device performs a bitwise logical AND between the destination IP address and the subnet mask. If the two network addresses match, the destination is on the local subnet and sent directly; if they differ, the packet is routed to the default gateway (router).

Marking scheme

1 mark (MP1): Purpose: Identifies/separates the Network ID portion from the Host ID portion in an IP address.
1 mark (MP2): Mechanism: A bitwise AND operation is performed between the subnet mask and the IP address.
0.5 marks (MP3): Decision: If the resulting network address matches the local network address, the packet is transmitted locally; otherwise, it is sent to the default gateway / router.

[Guidance: Award 1 mark for clear description of the bitwise comparison process even if the keyword 'AND' is described in operational terms.]
Question 3 · short-answer
2.5 marks
A desktop computer is sending print jobs to an external laser printer connected via USB.

Define the term buffer in the context of computer hardware, and explain why a buffer is required when data is transferred between the CPU and the printer.
Show answer & marking scheme

Worked solution

1. Definition: A buffer is a dedicated region of primary/temporary memory used to temporarily store data while it is moving from one subsystem or device to another.
2. Speed mismatch explanation: The processor and system bus operate at gigahertz speeds, whereas mechanical devices like printers process data much slower.
3. Role: The buffer absorbs the speed differential, enabling the CPU to release data in bulk and return to executing other processes without remaining idle or waiting for the printer to finish.

Marking scheme

1 mark (MP1): Definition: A temporary storage area / memory used to hold data in transit between two devices/components.
1 mark (MP2): Problem: To compensate for the speed mismatch / difference in data transfer rates between the fast CPU/memory and the slow peripheral (printer).
0.5 marks (MP3): Benefit: Prevents the CPU from being held up / allows the CPU to continue executing other tasks while printing occurs.

[Guidance: Accept 'queue' or 'temporary holding store' for MP1. Reject 'permanent storage'.]
Question 4 · short-answer
2.5 marks
During the execution of a user application, a hardware sensor raises an interrupt signal.

Describe the role of the Interrupt Service Routine (ISR) and explain how the CPU state is preserved before the ISR executes.
Show answer & marking scheme

Worked solution

1. Role: An ISR is a specific sequence of instructions that the processor executes to service/handle an interrupt source (e.g., handling hardware input, timer ticks, or error flags).
2. State preservation: At the end of the current Fetch-Execute cycle, the CPU pushes the current contents of key registers (such as the Program Counter (PC), Accumulator (ACC), Status Register) onto the stack.
3. Continuation: The PC is loaded with the start address of the ISR. Once the ISR concludes, the saved register states are popped from the stack, restoring the CPU state to resume the interrupted task.

Marking scheme

1 mark (MP1): Definition/Role: A dedicated routine / software routine that handles/processes the specific interrupt.
1 mark (MP2): State preservation: The contents of the registers / PC / Accumulator are pushed / saved to the stack.
0.5 marks (MP3): Restoration: Once the ISR finishes, register values are restored / popped to allow the interrupted process to continue from the exact point of suspension.

[Guidance: Must name or describe 'stack' or 'saving register contents' to award MP2. Do not accept simply 'saved in memory' without qualification.]
Question 5 · short-answer
2.5 marks
Software developers often link pre-compiled libraries when building desktop applications.

Define what is meant by a Dynamic Link Library (DLL) and state two advantages of using dynamic linking compared to static linking.
Show answer & marking scheme

Worked solution

1. Definition: A DLL contains modular code/subroutines that are linked to the main executable at execution/runtime instead of being embedded into the executable binary during compilation.
2. Advantage 1 (Memory/Storage efficiency): Multiple running programs can share one instance of a DLL in RAM simultaneously, reducing memory usage and keeping executable files smaller on disk.
3. Advantage 2 (Maintainability): When bug fixes or enhancements are made to the DLL, it can be updated independently without requiring all dependent programs to be recompiled or rebuilt.

Marking scheme

1 mark (MP1): Definition: Shared / pre-compiled library loaded and linked to the executable at runtime / execution time.
1.5 marks (MP2 & MP3): Any two valid advantages (0.75 marks each):
- Executable file size on disk is smaller
- Conserves main memory / RAM (multiple programs share the same DLL in memory)
- Modular maintenance / library can be updated without recompiling the main application
- Promotes code reusability across multiple independent software programs.

[Guidance: Reject 'faster execution speed' as an advantage, as dynamic loading incurs runtime overhead.]
Question 6 · short-answer
2.5 marks
A student registration portal requires applicants to submit personal contact details and academic grades.

Distinguish between data validation and data verification, and give one distinct example method for each.
Show answer & marking scheme

Worked solution

1. Data Validation: Software-based automated rule checks to confirm data is sensible, conforming to constraints (e.g., presence, length, range, format, check digit).
2. Example of Validation: Range check (e.g., age must be between 11 and 18) or Format check (e.g., postal code matches LLNN NLL).
3. Data Verification: Process to ensure data matches the original source or has not been corrupted during entry/transmission.
4. Example of Verification: Double entry (entering password twice) or Visual check (screen comparison against paper form) or Checksum / Parity.

Marking scheme

1 mark (MP1): Distinguishing definitions: Validation checks if data conforms to rules/is sensible/acceptable; Verification checks if data matches original source / entered accurately / not corrupted.
0.75 marks (MP2): Valid example of validation (e.g. range check, length check, presence check, format check, check digit, limit check).
0.75 marks (MP3): Valid example of verification (e.g. double entry, visual check, parity check, checksum).

[Guidance: Reject validation examples that claim to check 'correctness/truth of real-world facts'.]
Question 7 · short-answer
2.5 marks
An independent software vendor distributes a photo-editing tool under a shareware licence model.

State what is meant by shareware and describe two typical restrictions or conditions associated with this type of software licence.
Show answer & marking scheme

Worked solution

1. Meaning: Shareware is proprietary software distributed on a 'try before you buy' model for a limited evaluation period at no initial cost.
2. Condition 1 (Trial / expiration): Full or partial functionality ceases after a fixed duration (e.g., 14 or 30 days) unless paid for.
3. Condition 2 (Functional restriction / nag screens): Essential features (such as saving/printing) are locked, watermarks are added, or reminders to buy appear regularly.
4. Condition 3 (Copyright retention): The source code is closed/withheld, and reverse engineering or redistributing commercial versions is prohibited.

Marking scheme

1 mark (MP1): Definition: Copyrighted software provided free of charge on a trial/evaluation basis.
1.5 marks (MP2 & MP3): Any two typical restrictions (0.75 marks each):
- Time-limited trial period / stops working after a set number of days
- Feature-limited / key features disabled until payment/licence key entered
- Nag screens / purchase reminders presented to user
- Source code is not provided / user cannot modify or resell code.

[Guidance: Reject 'free software' without mention of trial/evaluation/licence fee.]
Question 8 · short-answer
2.5 marks
A relational database contains two tables: `Course` and `Enrolment`.

Define the term referential integrity, and explain how foreign keys are used to enforce referential integrity between related tables.
Show answer & marking scheme

Worked solution

1. Definition: Referential integrity ensures that references between related tables are valid and that data remains logically consistent across the relational database.
2. Mechanism: A foreign key in a child table (`Enrolment`) refers to the primary key of a parent table (`Course`).
3. Enforcement: The DBMS uses foreign key constraints to prevent orphan records, rejecting insertions of foreign keys that do not exist in the parent table, and blocking (or cascading) deletions of parent records that have linked child records.

Marking scheme

1 mark (MP1): Definition: A property/rule ensuring that foreign key values match an existing primary key in the referenced table (preventing inconsistent data/orphan records).
1 mark (MP2): Role of foreign key: Links a child table attribute to the primary key of a parent table.
0.5 marks (MP3): Enforcement action: DBMS prevents insertion of invalid foreign keys OR prevents deletion of parent records that have matching foreign key records.

[Guidance: Accept mention of 'cascade delete' as a valid enforcement mechanism for MP3.]
Question 9 · short_answer
2.5 marks
A digital archive converts scanned monochrome technical schematics into digital files and uses Run-Length Encoding (RLE) to reduce storage requirements.

(a) Define the term lossless compression. [1]
(b) Explain how Run-Length Encoding (RLE) reduces the file size of consecutive repeating data. [1.5]
Show answer & marking scheme

Worked solution

(a) Lossless compression is a compression technique where the file size is reduced without discarding any data, meaning the original file can be perfectly and identically restored when decompressed.

(b) In an uncompressed stream, every repeated byte/pixel is stored separately. RLE replaces a sequence of identical consecutive items with a pair of values: the run count (frequency) and the item value (e.g. colour code). This significantly decreases total byte count whenever long sequences of identical pixels occur.

Marking scheme

(a) 1 mark for any of the following:
- A compression method where no data/detail is lost / original file is reconstructed exactly / perfectly.
- [Reject: "file size is smaller" without mentioning perfect restoration / zero data loss]

(b) Max 1.5 marks:
- 0.75 mark: Identifies sequences of identical / repeated consecutive data values / pixels (runs).
- 0.75 mark: Replaces the sequence with a single value and a frequency count / run-length.
Question 10 · short_answer
2.5 marks
A software company distributes an enterprise system that makes use of Dynamic Link Library (DLL) files.

(a) Define what is meant by a Dynamic Link Library (DLL) file. [1]
(b) State one advantage and one disadvantage of using DLL files rather than static libraries. [1.5]
Show answer & marking scheme

Worked solution

(a) A Dynamic Link Library (DLL) is an external file containing pre-compiled procedures/code that are loaded into RAM and linked to an application dynamically during execution (runtime), rather than being compiled directly into the binary executable file.

(b) Advantage: Multiple applications can share a single copy in main memory, and the executable file size is smaller. Alternatively, bug fixes can be applied to the DLL without having to recompile the main executable.
Disadvantage: Dependency issues (e.g., if a DLL is missing or replaced by an incompatible version, the program crashes or fails to launch).

Marking scheme

(a) 1 mark for:
- Pre-compiled code/library of functions loaded/linked dynamically at runtime / into memory when needed.

(b) 1.5 marks total (0.75 mark per point):
- 0.75 mark for one valid advantage:
* Executable file size is reduced.
* Multiple programs/processes can share the same code in RAM.
* DLL can be updated / patched independently without recompiling the executable.
- 0.75 mark for one valid disadvantage:
* Program will not run if the required DLL file is missing / deleted / corrupted.
* Potential version incompatibility / DLL conflict ("DLL hell").
* Slight runtime overhead when resolving links dynamically.
Question 11 · theory
4 marks
A microprocessor unit in an automated ventilation system monitors environmental variables and processes numeric data in different formats.

(a) Convert the denary integer -77 into an 8-bit two's complement binary number. Show your working. [2]

(b) The system registers a sensor code given as the hexadecimal value 5E.

(i) Convert the hexadecimal value 5E into denary. [1]
(ii) Convert the hexadecimal value 5E into Binary Coded Decimal (BCD). [1]
Show answer & marking scheme

Worked solution

(a)
Step 1: Write positive 77 as an 8-bit binary number:
77 = 64 + 8 + 4 + 1 = 01001101

Step 2: Find the one's complement (invert all bits):
10110010

Step 3: Add 1 to find the two's complement:
10110010 + 1 = 10110011

(b)(i)
Convert hexadecimal 5E to denary:
5E = (5 * 16) + 14 = 80 + 14 = 94

(b)(ii)
Convert the denary value 94 to BCD:
Digit 9 = 1001
Digit 4 = 0100
Result: 1001 0100 (or 10010100)

Marking scheme

(a) [2 marks]
- 1 mark for showing valid working (e.g. converting +77 to 01001101 and inverting bits, or using place values -128 + 32 + 16 + 2 + 1)
- 1 mark for correct binary value: 10110011

(b)(i) [1 mark]
- 1 mark for 94

(b)(ii) [1 mark]
- 1 mark for 1001 0100 / 10010100 (Accept with or without space; reject any format not in 4-bit groups per decimal digit)
Question 12 · theory
4 marks
A high-altitude weather monitoring station records sensor values and transmits status bytes to a ground base.

(a) The processor uses 8-bit two's complement representation for temperature calculations. Perform binary addition on the following two 8-bit signed integers:

01001100
+ 00111010

State whether an arithmetic overflow has occurred and justify your answer. [2]

(b) A diagnostic status byte is received as the binary value 11011011.

(i) Convert 11011011 to hexadecimal. [1]
(ii) Convert 11011011 to an unsigned denary integer. [1]
Show answer & marking scheme

Worked solution

(a)
Addition:
01001100 (+76)
+ 00111010 (+58)
----------
10000110 (-122)

Overflow Analysis:
Both operands are positive (most significant bit is 0), but the result has an MSB of 1 (representing a negative number). In denary, 76 + 58 = 134, which is greater than the maximum positive value (+127) representable in 8-bit two's complement. Therefore, overflow has occurred.

(b)(i)
Split 11011011 into two 4-bit nibbles:
1101 = 13 = D
1011 = 11 = B
Result: DB (or &DB / 0xDB)

(b)(ii)
Convert unsigned binary 11011011 to denary:
128 + 64 + 16 + 8 + 2 + 1 = 219

Marking scheme

(a) [2 marks]
- 1 mark for correct binary sum: 10000110
- 1 mark for stating that overflow occurred with a valid justification (e.g. the addition of two positive numbers gave a negative result / 134 is outside the range -128 to +127)

(b)(i) [1 mark]
- 1 mark for DB (accept &DB, 0xDB, or lowercase db)

(b)(ii) [1 mark]
- 1 mark for 219
Question 13 · theory
5 marks
A wildlife research organisation uses a relational database to store information about field researchers and research expeditions.

The database has the following logical schema:

`RESEARCHER(ResearcherID, FirstName, LastName, Department, ContactNumber)`
`EXPEDITION(ExpeditionID, LocationName, StartDate, Budget, ResearcherID)`

(a) Write an SQL script to create the table `EXPEDITION`. Use appropriate data types for each attribute, and include the primary key and foreign key definitions. [3]

(b) Write an SQL query to display the `LocationName` and `Budget` of all expeditions led by researchers in the `'Marine Biology'` department. The results must be sorted in descending order of `Budget`. [2]
Show answer & marking scheme

Worked solution

(a) SQL DDL statement to create the table:
```sql
CREATE TABLE EXPEDITION (
ExpeditionID VARCHAR(8) NOT NULL,
LocationName VARCHAR(50),
StartDate DATE,
Budget REAL,
ResearcherID VARCHAR(6),
PRIMARY KEY (ExpeditionID),
FOREIGN KEY (ResearcherID) REFERENCES RESEARCHER(ResearcherID)
);
```
- Correct `CREATE TABLE EXPEDITION (...)` clause.
- Appropriate field data types: `ExpeditionID` (VARCHAR/CHAR), `LocationName` (VARCHAR/CHAR/TEXT), `StartDate` (DATE), `Budget` (REAL/INTEGER/CURRENCY), `ResearcherID` (VARCHAR/CHAR).
- Correct `PRIMARY KEY (ExpeditionID)` and `FOREIGN KEY (ResearcherID) REFERENCES RESEARCHER(ResearcherID)` declarations.

(b) SQL DML statement to query the required data:
```sql
SELECT LocationName, Budget
FROM EXPEDITION
INNER JOIN RESEARCHER ON EXPEDITION.ResearcherID = RESEARCHER.ResearcherID
WHERE Department = 'Marine Biology'
ORDER BY Budget DESC;
```
- Correct `SELECT` list with `FROM` and `INNER JOIN ... ON ...`.
- Correct `WHERE` clause matching `'Marine Biology'` and `ORDER BY Budget DESC`.

Marking scheme

(a) 1 mark for each of the following up to 3 marks:
- MP1: `CREATE TABLE EXPEDITION (` ... `);` with all 5 attributes declared.
- MP2: Appropriate data types used for all attributes (`ExpeditionID` as CHAR/VARCHAR, `LocationName` as CHAR/VARCHAR, `StartDate` as DATE, `Budget` as REAL/INTEGER/DECIMAL/CURRENCY, `ResearcherID` matching `RESEARCHER`).
- MP3: `PRIMARY KEY (ExpeditionID)` AND `FOREIGN KEY (ResearcherID) REFERENCES RESEARCHER(ResearcherID)` (both key definitions correct).

(b) 1 mark for each of the following up to 2 marks:
- MP1: `SELECT LocationName, Budget FROM EXPEDITION INNER JOIN RESEARCHER ON EXPEDITION.ResearcherID = RESEARCHER.ResearcherID` (Allow `FROM EXPEDITION, RESEARCHER WHERE EXPEDITION.ResearcherID = RESEARCHER.ResearcherID AND ...`).
- MP2: `WHERE Department = 'Marine Biology' ORDER BY Budget DESC` (Allow `RESEARCHER.Department` and `EXPEDITION.Budget`).
Question 14 · theory
5 marks
An astronomical observatory maintains a relational database to record information about telescopes and observation sessions.

The database includes the following two tables:

`TELESCOPE(TelescopeID, ModelName, ApertureSize, Location)`
`OBSERVATION(ObservationID, TargetObject, ObservationDate, DurationMinutes, TelescopeID)`

(a) Write an SQL script to alter the `TELESCOPE` table by adding a new attribute named `IsOperational` of data type `BOOLEAN`. [1]

(b) Write an SQL script to update the `DurationMinutes` to `120` for the record where `ObservationID` is `'OBS1042'`. [1]

(c) Write an SQL query to display the `ModelName` of each telescope and the total number of observations recorded for that telescope. Group the results by telescope model. [3]
Show answer & marking scheme

Worked solution

(a) Adding a column to an existing table:
```sql
ALTER TABLE TELESCOPE
ADD IsOperational BOOLEAN;
```

(b) Updating an existing record in the table:
```sql
UPDATE OBSERVATION
SET DurationMinutes = 120
WHERE ObservationID = 'OBS1042';
```

(c) Aggregating data across related tables:
```sql
SELECT TELESCOPE.ModelName, COUNT(OBSERVATION.ObservationID)
FROM TELESCOPE
INNER JOIN OBSERVATION ON TELESCOPE.TelescopeID = OBSERVATION.TelescopeID
GROUP BY TELESCOPE.ModelName;
```
- MP1: `SELECT TELESCOPE.ModelName, COUNT(...)` (or `COUNT(*)`).
- MP2: `FROM TELESCOPE INNER JOIN OBSERVATION ON TELESCOPE.TelescopeID = OBSERVATION.TelescopeID`.
- MP3: `GROUP BY TELESCOPE.ModelName` (or `GROUP BY TELESCOPE.TelescopeID, TELESCOPE.ModelName`).

Marking scheme

(a) 1 mark for:
- `ALTER TABLE TELESCOPE ADD IsOperational BOOLEAN;` (or `ADD COLUMN IsOperational BOOLEAN;`).

(b) 1 mark for:
- `UPDATE OBSERVATION SET DurationMinutes = 120 WHERE ObservationID = 'OBS1042';` (Award 0 marks if `WHERE` clause is missing or incorrect).

(c) 1 mark for each of the following up to 3 marks:
- MP1: `SELECT TELESCOPE.ModelName, COUNT(OBSERVATION.ObservationID)` / `COUNT(*)`.
- MP2: `FROM TELESCOPE INNER JOIN OBSERVATION ON TELESCOPE.TelescopeID = OBSERVATION.TelescopeID` (Allow Cartesian product with join condition in `WHERE`).
- MP3: `GROUP BY TELESCOPE.ModelName` (or `GROUP BY ModelName` / `GROUP BY TELESCOPE.TelescopeID, TELESCOPE.ModelName`).
Question 15 · Hardware / OS Concept Explanation
3 marks
A laboratory data-logger computer system contains both Static RAM (SRAM) and Dynamic RAM (DRAM).

Describe three differences in the construction or operation of SRAM and DRAM.
Show answer & marking scheme

Worked solution

Static RAM (SRAM) and Dynamic RAM (DRAM) differ fundamentally in their physical construction and operating principles:
1. Bit cell structure: DRAM stores each bit of data as an electrical charge in a tiny capacitor paired with a single transistor. SRAM stores each bit using a flip-flop latch made of 4 to 6 transistors.
2. Refresh requirement: The capacitor in DRAM continuously leaks electrical charge, so DRAM must be refreshed periodically (hundreds of times per second) to retain data. SRAM retains its data statically without refreshing as long as constant electrical power is maintained.
3. Speed and density: SRAM has much lower latency and faster access speeds than DRAM, but requires more silicon area per bit, making it lower density and more expensive. DRAM is denser and cheaper per bit, which is why DRAM is used for main memory and SRAM is used for cache memory.

Marking scheme

1 mark per valid point to a maximum of 3:
- MP1: Construction: DRAM uses a capacitor and a single transistor per bit cell, whereas SRAM uses multiple transistors / flip-flop circuit per bit cell.
- MP2: Refreshing: DRAM requires periodic refreshing / recharging (due to capacitor charge leakage), whereas SRAM does not require refreshing (as long as continuous power is supplied).
- MP3: Speed: SRAM has faster access times / lower latency than DRAM.
- MP4: Density / Cost: DRAM has higher storage density / smaller physical size per bit / is cheaper per bit than SRAM (or vice versa for SRAM).
- MP5: Power: DRAM consumes more dynamic power due to refreshing cycles / SRAM consumes less dynamic power.

Guidance:
- Accept comparative statements (e.g. 'DRAM is slower than SRAM').
- Do not award marks for simply stating 'SRAM is cache and DRAM is main memory' unless linked to the physical operational reason.
Question 16 · Logic Circuit Truth Table / Expression
2 marks
An automated laboratory incubator uses a monitoring system with three digital sensor inputs:

* \(T = 1\) if the temperature is above the safe threshold (otherwise \(T = 0\))
* \(H = 1\) if the humidity is below the required level (otherwise \(H = 0\))
* \(P = 1\) if the backup power unit is active (otherwise \(P = 0\))

An alert signal \(X = 1\) is generated when:
* the temperature is above the safe threshold AND the humidity is NOT below the required level
OR
* the humidity is below the required level AND the backup power unit is NOT active.

Write a logic expression for the alert signal output \(X\).
Show answer & marking scheme

Worked solution

1. Identify the first condition: 'temperature is above the safe threshold' (\(T\)) AND 'humidity is NOT below the required level' (\(\text{NOT } H\)) gives \(T \text{ AND NOT } H\).
2. Identify the second condition: 'humidity is below the required level' (\(H\)) AND 'backup power unit is NOT active' (\(\text{NOT } P\)) gives \(H \text{ AND NOT } P\).
3. Combine both conditions with the OR operator: \(X = (T \text{ AND NOT } H) \text{ OR } (H \text{ AND NOT } P)\).

Equivalent Boolean algebraic notations such as \(X = T.\overline{H} + H.\overline{P}\) or \(X = (T \land \neg H) \lor (H \land \neg P)\) are also acceptable.

Marking scheme

1 mark per correct part:
* 1 mark for both product terms correct: \((T \text{ AND NOT } H)\) and \((H \text{ AND NOT } P)\)
* 1 mark for full expression correctly combined with \(\text{OR}\) and equated to \(X\)

Accept equivalent Boolean algebraic notation: \(X = T\overline{H} + H\overline{P}\) or standard logic symbols.
Reject expressions with missing brackets that alter precedence.
Question 17 · Logic Circuit Truth Table / Expression
2 marks
A ventilation control unit produces an output \(X\) based on three sensor inputs \(A\), \(B\), and \(C\).

The logic expression for the system is:

\[X = (A \text{ NAND } B) \text{ XOR } C\]

Complete the truth table for this logic expression.

$$\begin{array}{|c|c|c|c|}
\hline
A & B & C & X \\
\hline
0 & 0 & 0 & \\
\hline
0 & 0 & 1 & \\
\hline
0 & 1 & 0 & \\
\hline
0 & 1 & 1 & \\
\hline
1 & 0 & 0 & \\
\hline
1 & 0 & 1 & \\
\hline
1 & 1 & 0 & \\
\hline
1 & 1 & 1 & \\
\hline
\end{array}$$
Show answer & marking scheme

Worked solution

Evaluate \(T_1 = A \text{ NAND } B\) first, then compute \(X = T_1 \text{ XOR } C\):

* For \(A=0, B=0, C=0\): \(T_1 = 1\), \(X = 1 \text{ XOR } 0 = 1\)
* For \(A=0, B=0, C=1\): \(T_1 = 1\), \(X = 1 \text{ XOR } 1 = 0\)
* For \(A=0, B=1, C=0\): \(T_1 = 1\), \(X = 1 \text{ XOR } 0 = 1\)
* For \(A=0, B=1, C=1\): \(T_1 = 1\), \(X = 1 \text{ XOR } 1 = 0\)
* For \(A=1, B=0, C=0\): \(T_1 = 1\), \(X = 1 \text{ XOR } 0 = 1\)
* For \(A=1, B=0, C=1\): \(T_1 = 1\), \(X = 1 \text{ XOR } 1 = 0\)
* For \(A=1, B=1, C=0\): \(T_1 = 0\), \(X = 0 \text{ XOR } 0 = 0\)
* For \(A=1, B=1, C=1\): \(T_1 = 0\), \(X = 0 \text{ XOR } 1 = 1\)

Marking scheme

1 mark for the first 4 rows correct (1, 0, 1, 0)
1 mark for the last 4 rows correct (1, 0, 0, 1)
Question 18 · Discussion / Evaluation
4 marks
A regional parcel distribution centre is planning to deploy an Artificial Intelligence (AI) automated sorting and transport system to replace human forklift operators and manual parcel sorters.

Discuss the social and economic impacts on the workforce and the company of introducing this AI-based system.
Show answer & marking scheme

Worked solution

To gain full marks, candidates must provide points covering both social and economic aspects.

Economic impacts:
- High initial implementation costs (capital expenditure on hardware, software development, installation, and integration).
- Long-term cost savings due to reduced wage bills, employee benefits, and human resource overheads.
- Higher throughput/productivity because machines can run 24 hours a day, 7 days a week with consistent sorting accuracy.
- Costs associated with system maintenance, software updates, and training technical support personnel.

Social impacts:
- Loss of employment/redundancies for manual workers leading to anxiety, stress, or lower morale.
- Safer working conditions by eliminating manual heavy-lifting and collision hazards involving human-driven vehicles.
- Requirement for workforce upskilling/reskilling, offering remaining employees career progression into technical or supervisory roles.
- Potential employee resistance to organizational change and technology adoption.

Marking scheme

1 mark per valid point up to a maximum of 4 marks.
Award a maximum of 3 marks if only social OR only economic impacts are discussed.

Economic impacts (max 3):
- High initial capital expenditure / setup / purchasing / installation cost [1]
- Reduction in ongoing wage bills / long-term operational labor costs [1]
- Increased productivity / continuous 24/7 operation without breaks [1]
- Costs required for ongoing maintenance / technical upgrades / system repairs [1]

Social impacts (max 3):
- Redundancies / unemployment / loss of jobs leading to financial stress / reduced morale [1]
- Improved health and safety / reduction in human workplace accidents and injuries [1]
- Need for retraining / upskilling into supervisory or technical roles [1]
- Resistance to change / anxiety about future job stability [1]

Reject:
- Vague statements such as 'makes things better' or 'cheaper' without context.
- Points unrelated to the given scenario.

Ready to test yourself?

Turn these notes into exam-style practice. Get unlimited AI questions on this topic with instant marking and explanations.

Practise This Topic

Paper 2 Fundamental Problem-solving and Programming Skills

Answer all questions. Refer to the insert for pseudocode functions. Do not use language-specific library functions.
11 Question · 51.49 marks
Question 1 · free-response
3.33 marks
A logistics system uses an identification string called `ParcelID`. A valid `ParcelID` must satisfy the following validation rules:

* Rule 1: It must be exactly 7 characters in length.
* Rule 2: The first two characters must be uppercase alphabetic letters (`'A'` to `'Z'`).
* Rule 3: The next four characters (positions 3 to 6) must be numeric digits (`'0'` to `'9'`).
* Rule 4: The final character (position 7) must be an exclamation mark (`'!'`).

The function `ValidateParcelID` takes `ParcelID : STRING` as a parameter and returns `TRUE` if the string is valid, or `FALSE` otherwise.

Complete the following pseudocode by writing the missing lines or expressions corresponding to labels [Line 1], [Line 2], and [Line 3].

```text
FUNCTION ValidateParcelID(ParcelID : STRING) RETURNS BOOLEAN
DECLARE Index : INTEGER
DECLARE NextChar : CHAR

IF LENGTH(ParcelID) <> 7 THEN
RETURN FALSE
ENDIF

// Check characters 1 and 2
FOR Index <- 1 TO 2
NextChar <- MID(ParcelID, Index, 1)
IF NextChar < 'A' OR NextChar > 'Z' THEN
RETURN FALSE
ENDIF
NEXT Index

// Check characters 3 to 6
FOR Index <- 3 TO 6
NextChar <- MID(ParcelID, Index, 1)
[Line 1]
RETURN FALSE
ENDIF
NEXT Index

// Check final character
[Line 2]
RETURN FALSE
ENDIF

[Line 3]
ENDFUNCTION
```
Show answer & marking scheme

Worked solution

To complete the function according to the validation rules:

1. [Line 1]: For characters at positions 3 to 6, the rule requires numeric digits (`'0'` to `'9'`). The condition checks whether the character is outside this range: `IF NextChar < '0' OR NextChar > '9' THEN` (or `IF NOT (NextChar >= '0' AND NextChar <= '9') THEN`).
2. [Line 2]: For the final character (position 7), Rule 4 states it must be `'!'`. If it is not `'!'`, the function returns `FALSE`. Therefore: `IF MID(ParcelID, 7, 1) <> '!' THEN` or `IF RIGHT(ParcelID, 1) <> '!' THEN`.
3. [Line 3]: If the string has passed all tests without returning `FALSE`, it is valid, so the function must return `TRUE`: `RETURN TRUE`.

Marking scheme

1 mark per correct line / section (total 3.33 marks across points):
- [Line 1]: `IF NextChar < '0' OR NextChar > '9' THEN` (Accept equivalent Boolean expressions such as `IF NOT(NextChar >= '0' AND NextChar <= '9') THEN`. Allow single quotes or double quotes around character literals. Reject syntax with missing `THEN`).
- [Line 2]: `IF MID(ParcelID, 7, 1) <> '!' THEN` (Accept `IF RIGHT(ParcelID, 1) <> '!' THEN` or `IF MID(ParcelID, 7, 1) = '!' THEN` inverted logic with appropriate branching. Reject 0-based index `MID(ParcelID, 6, 1)`).
- [Line 3]: `RETURN TRUE` (Reject `OUTPUT TRUE` or `ValidateParcelID <- TRUE`).
Question 2 · free-response
3.33 marks
A program reads a customer's loyalty discount rate from user input. The input must satisfy the following validation criteria:
- It must be a real number.
- It must be in the range 0.0 to 35.0 inclusive.

The user must be repeatedly prompted to re-enter the discount rate until a valid value is entered. The procedure must count how many invalid attempts were made and output a warning message `"Multiple invalid attempts"` if more than 2 invalid values were entered before a valid one was supplied.

Complete the following pseudocode for the procedure `InputDiscountRate`.

```text
PROCEDURE InputDiscountRate()
DECLARE Rate : REAL
DECLARE InvalidCount : INTEGER

InvalidCount <- 0

REPEAT
OUTPUT "Enter discount rate (0.0 - 35.0): "
INPUT Rate

IF [Condition 1] THEN
OUTPUT "Error: Value out of range."
[Statement 1]
ENDIF
UNTIL [Condition 2]

IF [Condition 3] THEN
OUTPUT "Multiple invalid attempts"
ENDIF
ENDPROCEDURE
```
Show answer & marking scheme

Worked solution

1. [Condition 1]: The validation condition inside the loop checks if the entered rate is out of bounds (less than 0.0 or greater than 35.0). Therefore: `Rate < 0.0 OR Rate > 35.0`.
2. [Statement 1]: Each time an invalid rate is entered, the counter for invalid entries must be incremented by 1: `InvalidCount <- InvalidCount + 1`.
3. [Condition 2]: A `REPEAT ... UNTIL` loop terminates when its condition evaluates to `TRUE`. The loop should terminate when the entered rate is valid: `Rate >= 0.0 AND Rate <= 35.0` (or `NOT (Rate < 0.0 OR Rate > 35.0)`).
4. [Condition 3]: The requirement states that the warning must be output if more than 2 invalid attempts were made. Therefore: `InvalidCount > 2`.

Marking scheme

Mark points (total 3.33 marks):
- [Condition 1]: `Rate < 0.0 OR Rate > 35.0` (Accept `Rate < 0 OR Rate > 35`; Reject `AND` in place of `OR`).
- [Statement 1]: `InvalidCount <- InvalidCount + 1` (Accept `InvalidCount := InvalidCount + 1` or `InvalidCount = InvalidCount + 1`).
- [Condition 2]: `Rate >= 0.0 AND Rate <= 35.0` (Accept `NOT (Rate < 0.0 OR Rate > 35.0)`).
- [Condition 3]: `InvalidCount > 2` (Accept `InvalidCount >= 3`; Reject `InvalidCount >= 2`).
Question 3 · free-response
3.33 marks
A school generates a check code for student registration numbers.

A registration string `RegNum` contains 5 numeric characters (e.g. `"48291"`). The validation function `GenerateCheckDigit` computes a single check digit using the following algorithm:
1. Extract each numeric digit from position 1 to 5.
2. Multiply the digit at position 1 by 1, position 2 by 2, position 3 by 3, position 4 by 4, and position 5 by 5.
3. Sum these products together into `Total`.
4. The check digit is the remainder when `Total` is divided by 10 (`Total MOD 10`).
5. Return the check digit as a single `CHAR`.

Complete the following pseudocode function by filling in the missing expressions or statements for [Gap 1], [Gap 2], and [Gap 3].

```text
FUNCTION GenerateCheckDigit(RegNum : STRING) RETURNS CHAR
DECLARE Index : INTEGER
DECLARE Total : INTEGER
DECLARE Digit : INTEGER

Total <- 0

FOR Index <- 1 TO 5
// Convert extracted character at Index to an integer value
Digit <- [Gap 1]

// Accumulate weighted product
Total <- [Gap 2]
NEXT Index

// Return the single character check digit
RETURN [Gap 3]
ENDFUNCTION
```
Show answer & marking scheme

Worked solution

1. [Gap 1]: The character at position `Index` is extracted using `MID(RegNum, Index, 1)` and converted to an integer via the built-in function `STR_TO_NUM(MID(RegNum, Index, 1))`.
2. [Gap 2]: The product of the digit and its position index `(Digit * Index)` is added to the running sum: `Total + (Digit * Index)`.
3. [Gap 3]: The remainder of `Total` divided by 10 is found using `Total MOD 10`. Because the function return type is `CHAR`, this integer result must be converted to a character string: `NUM_TO_STR(Total MOD 10)` (or `CHR(ASC('0') + Total MOD 10)`).

Marking scheme

Mark points (total 3.33 marks):
- [Gap 1]: `STR_TO_NUM(MID(RegNum, Index, 1))` (Accept `ASC(MID(RegNum, Index, 1)) - 48` or `ASC(MID(RegNum, Index, 1)) - ASC('0')`).
- [Gap 2]: `Total + (Digit * Index)` (Accept `Total + Digit * Index`).
- [Gap 3]: `NUM_TO_STR(Total MOD 10)` (Accept `CHR((Total MOD 10) + 48)` or `CHR(ASC('0') + (Total MOD 10))`; Reject integer without conversion since return type is `CHAR`).
Question 4 · free-response
2.5 marks
A software developer has written a sub-routine `CalculateTax()` to compute sales duty on imported goods.

(a) Describe the difference between white-box testing and black-box testing. [2]
(b) State which of these two testing methods is required to perform code path coverage analysis. [0.5]
Show answer & marking scheme

Worked solution

(a)
- White-box testing involves examining and executing the internal logic, algorithms, and branches within the source code to ensure all execution paths behave as intended.
- Black-box testing evaluates inputs and expected outputs against specification requirements without knowledge or visibility of the underlying source code.

(b) Code path coverage requires direct analysis of the internal code structure, control flow, and branches, which is exclusively an aspect of white-box testing.

Marking scheme

(a) 1 mark per discrete point (max 2):
- MP1: White-box testing examines the internal structure/logic/code/algorithms of the module. [1]
- MP2: Black-box testing tests program behaviour/inputs and outputs against specifications without reference to the source code/internal structure. [1]

(b) 0.5 marks:
- White-box (testing) [0.5]
(Reject: Black-box)
Question 5 · Abstract Data Type Tracing & Explanation
4.5 marks
A linear queue, `RequestQueue`, is implemented using a 1D array of size 5 with indices from 1 to 5.

Two pointer variables are used:
- `HeadPointer` points to the index of the first item in the queue.
- `TailPointer` points to the index of the last item in the queue.

When the queue is empty, `HeadPointer` is set to 0 and `TailPointer` is set to 0.

(a) The queue is initially empty. The following sequence of operations is executed in order:
1. `Enqueue("PrintDocA")`
2. `Enqueue("ScanDocB")`
3. `Enqueue("EmailDocC")`
4. `Dequeue()`
5. `Enqueue("FaxDocD")`

State the contents of each index (1 to 5) of the `RequestQueue` array, and state the final values of `HeadPointer` and `TailPointer`. [2.5]

(b) Explain why a linear queue implemented in a fixed-size array can report a "queue full" condition when empty spaces still exist in the array. State how this issue can be resolved without shifting elements. [2.0]
Show answer & marking scheme

Worked solution

(a)
- Initial: HeadPointer = 0, TailPointer = 0
- Enqueue("PrintDocA"): HeadPointer = 1, TailPointer = 1, RequestQueue[1] = "PrintDocA"
- Enqueue("ScanDocB"): HeadPointer = 1, TailPointer = 2, RequestQueue[2] = "ScanDocB"
- Enqueue("EmailDocC"): HeadPointer = 1, TailPointer = 3, RequestQueue[3] = "EmailDocC"
- Dequeue(): removes "PrintDocA", HeadPointer increments to 2
- Enqueue("FaxDocD"): HeadPointer = 2, TailPointer = 4, RequestQueue[4] = "FaxDocD"

Final Array State:
- Index 1: Empty / Logically deleted
- Index 2: "ScanDocB"
- Index 3: "EmailDocC"
- Index 4: "FaxDocD"
- Index 5: Empty / Unused

Final Pointer Values:
- HeadPointer = 2
- TailPointer = 4

(b)
- Reason: As items are dequeued, `HeadPointer` moves forward, leaving unused elements at the lower end of the array. Since new items are only appended at `TailPointer`, once `TailPointer` reaches the upper bound (index 5), no more items can be inserted even though total elements < capacity.
- Resolution: Implement a circular queue (ring buffer) where `TailPointer` wraps around to index 1 when free space exists at the start.

Marking scheme

(a) 1 mark for correct array contents at indices 2, 3, 4 ("ScanDocB", "EmailDocC", "FaxDocD").
1 mark for identifying index 1 and 5 as empty/unused/inactive.
0.5 mark for both HeadPointer = 2 and TailPointer = 4.

(b) 1 mark for explaining that `TailPointer` reaches the upper bound/maximum index while vacant slots remain before `HeadPointer`.
1 mark for stating that a circular queue is used (or describing pointer wrap-around to index 1).
Question 6 · Abstract Data Type Tracing & Explanation
4.5 marks
A linked list stores student ID codes in alphabetical order. The linked list is implemented using two 1D arrays, `CandidateCode` of type `STRING` and `NextPointer` of type `INTEGER`, both with indices from 1 to 6.

- `StartPointer` stores the index of the first node in the list.
- `FreePointer` stores the index of the first available node in the free list.
- A pointer value of `0` represents a null pointer.

The current contents of the data structure are shown below:

| Index | CandidateCode | NextPointer |
|---|---|---|
| 1 | "C14" | 5 |
| 2 | "B09" | 1 |
| 3 | "E82" | 0 |
| 4 | "" | 6 |
| 5 | "D55" | 3 |
| 6 | "" | 0 |

`StartPointer = 2`
`FreePointer = 4`

(a) State the sequence of candidate codes currently stored in the linked list, in logical order from first to last. [1.5]

(b) A new code, `"C90"`, is inserted into the linked list in its correct alphabetical position.
State:
(i) The index where `"C90"` is stored. [0.5]
(ii) The updated value of `FreePointer`. [0.5]
(iii) The updated values of `NextPointer[1]`, `NextPointer[4]`, and `NextPointer[6]`. (State 'unchanged' if a value does not change). [2.0]
Show answer & marking scheme

Worked solution

(a) Trace from StartPointer (2):
- Node 2: "B09", NextPointer = 1
- Node 1: "C14", NextPointer = 5
- Node 5: "D55", NextPointer = 3
- Node 3: "E82", NextPointer = 0 (end of list)
Logical order: "B09", "C14", "D55", "E82"

(b)
(i) The new node is taken from `FreePointer`, which is index 4.
(ii) `FreePointer` updates to `NextPointer[4]`, which is 6.
(iii) "C90" falls alphabetically between "C14" (index 1) and "D55" (index 5):
- The node at index 1 must now point to the new node at index 4: `NextPointer[1] = 4`
- The new node at index 4 must point to the node at index 5: `NextPointer[4] = 5`
- The node at index 6 remains in the free list: `NextPointer[6] = 0` (unchanged).

Marking scheme

(a) 1.5 marks for the complete, correct sequence: "B09", "C14", "D55", "E82" (Award 1 mark if 3 out of 4 are correct in order).
(b)(i) 0.5 mark for index 4.
(b)(ii) 0.5 mark for FreePointer = 6.
(b)(iii) 1 mark for NextPointer[1] = 4.
0.5 mark for NextPointer[4] = 5.
0.5 mark for NextPointer[6] = 0 / unchanged.
Question 7 · Algorithm Description
6 marks
A 1D array SensorReadings contains 200 REAL values representing temperature readings recorded at regular intervals.

An algorithm is required to process the data in SensorReadings to:
- find the highest temperature reading and the lowest temperature reading
- calculate the average (mean) temperature
- count the number of temperature readings that are strictly greater than 35.0
- output the highest reading, lowest reading, average reading, and the count of readings greater than 35.0.

Describe the algorithm using a step-by-step description or structured English.

Do not write pseudocode or program code.
Show answer & marking scheme

Worked solution

Step 1: Set a running total to 0 and a counter for readings above 35.0 to 0.
Step 2: Initialize both highest reading and lowest reading to the value of the first element in SensorReadings (SensorReadings[1]).
Step 3: Iterate through each element in SensorReadings from index 1 to index 200 (or index 2 to 200 if index 1 is already handled).
Step 4: In each iteration, add the current element's value to the running total.
Step 5: Compare the current element to the highest reading; if it is greater, update the highest reading.
Step 6: Compare the current element to the lowest reading; if it is lower, update the lowest reading.
Step 7: Compare the current element to 35.0; if it is strictly greater than 35.0, add 1 to the count of readings above 35.0.
Step 8: After completing the iteration across all 200 elements, compute the average by dividing the running total by 200.
Step 9: Output the final values: highest reading, lowest reading, calculated average, and count of readings above 35.0.

Marking scheme

Award 1 mark for each of the following (max 6 marks):
1. Initialize running total / sum to 0 AND counter for > 35.0 to 0.
2. Initialize highest and lowest variables appropriately (e.g. to the first array element SensorReadings[1], or suitable extreme values).
3. Loop through all 200 elements in the array (e.g. from index 1 to 200).
4. Accumulate sum / running total AND compare each value to 35.0 to increment the counter.
5. Compare each array element to update highest and lowest values.
6. Calculate the average by dividing total sum by 200 AND output all four required values (highest, lowest, average, count).
Question 8 · structured
4 marks
A programmer writes the following pseudocode procedure to sort an array `ReadingValues` of 100 integers into ascending numerical order:

```pseudocode
PROCEDURE BubbleSort(ReadingValues : ARRAY)
DECLARE Outer : INTEGER
DECLARE Inner : INTEGER
DECLARE Temp : INTEGER
FOR Outer <- 1 TO 99
FOR Inner <- 1 TO 99
IF ReadingValues[Inner] > ReadingValues[Inner + 1] THEN
Temp <- ReadingValues[Inner]
ReadingValues[Inner] <- ReadingValues[Inner + 1]
ReadingValues[Inner + 1] <- Temp
ENDIF
NEXT Inner
NEXT Outer
ENDPROCEDURE
```

(a) State two modifications that can be made to this algorithm to improve its efficiency.

(b) Explain the effect of using a swap-tracking boolean flag when the array `ReadingValues` is already in ascending order before the procedure is called.
Show answer & marking scheme

Worked solution

(a)
1. Decrease the number of inner comparisons on each iteration: After pass `Outer`, the largest `Outer` items are already in their final correct positions, so the inner loop can run `FOR Inner <- 1 TO (100 - Outer)`.
2. Add an early exit mechanism: Set a boolean flag `Swapped <- FALSE` before the inner loop, set `Swapped <- TRUE` inside the `IF` block when a swap occurs, and terminate the outer loop if `Swapped` remains `FALSE` at the end of a pass.

(b)
If the array is already sorted:
- On the very first pass, the condition `ReadingValues[Inner] > ReadingValues[Inner + 1]` is never true.
- No swaps occur, so `Swapped` remains `FALSE`.
- The algorithm terminates after only 1 pass (99 comparisons) rather than executing all 99 outer loop passes (which would require \(99 \times 99 = 9801\) comparisons in the unoptimized version).

Marking scheme

(a) Award 1 mark per valid optimization (Max 2):
- MP1: Reduce inner loop limit / range by `Outer` / run inner loop to `100 - Outer` / `99 - Outer + 1` [1]
- MP2: Use a boolean flag to track whether any swaps were made during a pass [1]
- MP3: Change outer loop to a pre-condition or post-condition loop (`WHILE` / `REPEAT...UNTIL`) to terminate when no swaps occur [1]

(b) Award 1 mark for each point (Max 2):
- MP1: In the first pass, no swaps take place / flag remains `FALSE` [1]
- MP2: Algorithm terminates immediately after the first pass / completes only 99 comparisons instead of all 99 passes / avoids redundant passes [1]
Question 9 · structured
4 marks
A linear search function is designed to search for `TargetID` in a 1D array `CustomerID` containing 500 distinct integers. The array `CustomerID` is already sorted in ascending numerical order.

The initial algorithm is written as follows:

```pseudocode
FUNCTION SearchID(TargetID : INTEGER) RETURNS INTEGER
DECLARE Index : INTEGER
DECLARE FoundIndex : INTEGER
FoundIndex <- -1
FOR Index <- 1 TO 500
IF CustomerID[Index] = TargetID THEN
FoundIndex <- Index
ENDIF
NEXT Index
RETURN FoundIndex
ENDFUNCTION
```

(a) Describe how the loop structure can be altered so that the search terminates as soon as `TargetID` is located.

(b) Explain how the fact that `CustomerID` is sorted in ascending order can be used to optimize the search when `TargetID` is not present in the array.
Show answer & marking scheme

Worked solution

(a)
To terminate immediately upon finding the target:
1. Replace the `FOR` loop with a `WHILE` loop: initialize `Index <- 1` and loop condition `WHILE Index <= 500 AND FoundIndex = -1`.
2. Increment `Index <- Index + 1` manually inside the loop.
(Alternative: execute `RETURN Index` immediately inside the `IF` statement when a match is found).

(b)
Because the array is sorted in ascending order:
- If an element `CustomerID[Index]` is encountered that is strictly greater than `TargetID`, `TargetID` cannot appear anywhere later in the array.
- The function can stop searching immediately and return `-1`, avoiding unnecessary comparisons through the remainder of the 500 elements.

Marking scheme

(a) Award 1 mark for each point (Max 2):
- MP1: Replace `FOR` loop with a `WHILE` loop / `REPEAT...UNTIL` loop [1]
- MP2: Add a condition that checks if the item is not yet found / `FoundIndex = -1` (alongside `Index <= 500`) [1]
(Accept: Return `Index` immediately when `CustomerID[Index] = TargetID` [1] and return `-1` after the loop [1])

(b) Award 1 mark for each point (Max 2):
- MP1: Check if the current array value is greater than `TargetID` (`CustomerID[Index] > TargetID`) [1]
- MP2: Terminate the search immediately because all subsequent values in the sorted array will also be greater than `TargetID` [1]
Question 10 · Long Form Pseudocode Module Writing (Function / Procedure)
8 marks
An international shipping company requires a function to validate parcel tracking reference codes.

A tracking code is passed to the function as a string parameter, `TrackingCode`.

A valid tracking code must satisfy the following rules:
1. It must be exactly 8 characters in length.
2. The first two characters must both be uppercase alphabetic letters (`'A'` to `'Z'`).
3. Characters 3 to 7 (inclusive) must all be numeric digits (`'0'` to `'9'`).
4. Character 8 is a check character calculated from characters 3 to 7:
- Calculate the sum of the numerical values of the 5 digits (characters 3 to 7).
- Determine the remainder when this sum is divided by 26.
- The expected check character is the uppercase letter at position `Remainder` in the alphabet, where 0 corresponds to `'A'`, 1 to `'B'`, ..., and 25 to `'Z'`.
- Character 8 must match this calculated letter.

Write pseudocode for the function `ValidateTrackingCode`.

You should assume that the following built-in functions are available:
- `LENGTH(Str : STRING) RETURNS INTEGER` — returns the number of characters in `Str`.
- `MID(Str : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING` — returns a substring of length `Length` starting at position `Start`.
- `ASC(Char : CHAR) RETURNS INTEGER` — returns the ASCII value of character `Char`.
- `CHR(Code : INTEGER) RETURNS CHAR` — returns the character corresponding to ASCII value `Code`.
Show answer & marking scheme

Worked solution

To validate the tracking code, the function executes the following stepwise logic:
1. Check the length of `TrackingCode`. If `LENGTH(TrackingCode) <> 8`, immediately set validity to `FALSE` or return `FALSE`.
2. Iterate through index 1 to 2 using `MID(TrackingCode, Index, 1)` and verify that each character is an uppercase letter (ASCII code between 65 and 90 inclusive).
3. Initialise an accumulator `SumDigits ← 0`.
4. Iterate through index 3 to 7 using `MID(TrackingCode, Index, 1)` and verify that each character is a numeric digit (ASCII code between 48 and 57 inclusive). For each valid digit, calculate its integer value `ASC(CurrentChar) - 48` and add it to `SumDigits`.
5. Calculate the remainder using `SumDigits MOD 26`.
6. Determine the expected check character using `CHR(65 + Remainder)` (since ASCII 65 = 'A').
7. Compare character 8 `MID(TrackingCode, 8, 1)` with `ExpectedCheckChar`. If they do not match, set validity to `FALSE`.
8. Return the boolean result.

Marking scheme

1 mark per point up to max 8 marks:
1. Correct `FUNCTION` header with parameter name, string type, and `RETURNS BOOLEAN`, plus `ENDFUNCTION`.
2. Correct check that length of string is equal to 8 (e.g. `IF LENGTH(TrackingCode) <> 8`).
3. Loop / check verifying both characters 1 and 2 are uppercase letters ('A' to 'Z' or ASCII 65 to 90).
4. Loop through characters 3 to 7 testing that each character is a digit ('0' to '9' or ASCII 48 to 57).
5. Correct conversion of character digit to numeric integer value AND accumulating sum of digits 3 to 7.
6. Correct calculation of remainder using `MOD 26` on the sum.
7. Correct derivation of expected check letter using `CHR(65 + Remainder)` or `CHR(ASC('A') + Remainder)`.
8. Comparison of character 8 with expected check letter AND returning boolean result (`TRUE` or `FALSE`).

Guidance Notes:
- Reject direct string conversion without handling non-digit errors unless validated beforehand.
- Allow direct relational comparisons such as `CurrentChar >= 'A' AND CurrentChar <= 'Z'`.
Question 11 · Long Form Pseudocode Module Writing (Function / Procedure)
8 marks
A company records employee professional development data in a text file named `CourseLog.txt`.

Each line of the text file contains a single record in the format:
`EmployeeID*DepartmentCode*HoursTrained`

For example:
`"EMP304*IT*14.5"`

- `EmployeeID` is a 6-character string.
- `DepartmentCode` is a 2-character string.
- `HoursTrained` is a real number stored as a string.
- Asterisk characters (`'*'`) are used as delimiters between fields.

A procedure `GenerateTrainingReport` is required to:
- Take a target department code string `TargetDept` as a parameter.
- Open the text file `CourseLog.txt` in read mode.
- Read each record sequentially until the end of the file.
- Extract the three fields (`EmployeeID`, `DepartmentCode`, and `HoursTrained`).
- If `DepartmentCode` matches `TargetDept`:
- Count the matching employee record.
- Add `HoursTrained` to a total training hours accumulator.
- If `HoursTrained` is less than 10.0, output the message: ` & " - Needs Further Training"`.
- Close the file `CourseLog.txt`.
- If one or more matching records were found, calculate and output the average training hours for that department in the format: `"Average hours: " & AverageHours`. Otherwise, output: `"No records found for department: " & TargetDept`.

Write pseudocode for the procedure `GenerateTrainingReport`.

You should assume that the following built-in functions are available:
- `LENGTH(Str : STRING) RETURNS INTEGER`
- `MID(Str : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING`
- `STR_TO_REAL(Str : STRING) RETURNS REAL` — converts a numeric string to a real number.
Show answer & marking scheme

Worked solution

The procedure performs the following steps:
1. Declare local variables and initialise `Count ← 0` and `TotalHours ← 0.0`.
2. Open `CourseLog.txt` for reading using `OPENFILE "CourseLog.txt" FOR READ`.
3. Loop until `EOF("CourseLog.txt")` is TRUE, reading each line using `READFILE`.
4. Locate the two `*` delimiters by iterating through `CurrentLine`.
5. Extract `EmpID`, `Dept`, and `HoursStr` using `MID` based on delimiter positions (or fixed offsets since `EmpID` is 6 chars and `Dept` is 2 chars).
6. Compare `Dept` to `TargetDept`. If they match:
- Convert `HoursStr` to real `Hours` using `STR_TO_REAL(HoursStr)`.
- Increment `Count ← Count + 1`.
- Add `Hours` to `TotalHours`.
- Check if `Hours < 10.0` and output ` & " - Needs Further Training"`.
7. Close the file `CLOSEFILE "CourseLog.txt"`.
8. Check if `Count > 0`: if true, calculate `AverageHours ← TotalHours / Count` and output the result; otherwise, output `"No records found for department: " & TargetDept`.

Marking scheme

1 mark per point up to max 8 marks:
1. Correct `PROCEDURE` header with parameter `TargetDept : STRING` AND `ENDPROCEDURE`.
2. Initialising `Count` to 0 AND `TotalHours` to 0.0 (or 0).
3. Correct file handling: `OPENFILE "CourseLog.txt" FOR READ` AND `CLOSEFILE "CourseLog.txt"`.
4. Correct file loop using `WHILE NOT EOF("CourseLog.txt")` AND `READFILE "CourseLog.txt", CurrentLine`.
5. Correct string extraction to obtain `EmployeeID`, `DepartmentCode`, and `HoursTrained` string.
6. Converting extracted hours string to REAL using `STR_TO_REAL(...)`.
7. Comparison of extracted department with `TargetDept`, incrementing `Count`, accumulating `TotalHours`, and conditional check for `Hours < 10.0` with correct output.
8. Post-loop check on `Count > 0` with correct calculation/output of average hours AND correct alternative message when `Count = 0`.

Guidance Notes:
- Award MP5 if fixed-position extraction is used (e.g. `MID(CurrentLine, 1, 6)`, `MID(CurrentLine, 8, 2)`, `MID(CurrentLine, 11, LENGTH(CurrentLine) - 10)`).
- Reject missing `CLOSEFILE` or misplaced outside module body.

Wondering how well you actually know this?

thinka is an AI practice app for DSE students: unlimited questions, instant auto-marking, and detailed step-by-step solutions. 100,000+ students use it to confirm they actually know it, not just think they do.

Want more questions like this? Practise unlimited on thinka, instant answers included.

Start Practising Free