Cambridge IAS-Level · Thinka-original Practice Paper

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

Thinka Nov 2023 (V1) Cambridge International A Level-Style Mock — Computer Science (9618)

150 marks210 mins2023
An original Thinka practice paper modelled on the structure and difficulty of the Nov 2023 (V1) Cambridge International A Level Computer Science (9618) paper. Not affiliated with or reproduced from Cambridge.

Paper 1 Theory Fundamentals

Answer all questions. Calculators must not be used in this paper.
9 Question · 42 marks
Question 1 · Recall & Description
4 marks
Explain the differences between immediate addressing and direct addressing in assembly language. Provide an example of a typical instruction for each addressing mode to illustrate your answer.
Show answer & marking scheme

Worked solution

In immediate addressing, the operand field contains the actual data value to be used by the instruction, and no memory access is required to fetch the data. Example: LDM #45 loads the value 45 directly into the Accumulator.
In direct addressing, the operand field contains the memory address where the target data is stored. The processor must perform a memory read operation to retrieve the value from that address. Example: LDD 45 loads the contents of memory address 45 into the Accumulator.

Marking scheme

1 mark: Correct description of immediate addressing (value is directly inside the instruction's operand).
1 mark: Valid assembly example of immediate addressing (e.g., LDM #45, with '#' indicating immediate value).
1 mark: Correct description of direct addressing (operand contains the memory address of the operand value).
1 mark: Valid assembly example of direct addressing (e.g., LDD 45 or LDD address).
Question 2 · Recall & Description
4 marks
An operating system (OS) typically includes utility software. Identify two utility programs and describe how each helps maintain the computer system.
Show answer & marking scheme

Worked solution

1. Disk Defragmenter: When files are created, modified, or deleted, they become fragmented across a mechanical hard drive, increasing access times. A disk defragmenter reorganizes these file segments into contiguous blocks, which reduces disk-head movement and restores file-read efficiency.
2. Backup Software: This utility automatically or manually duplicates essential files to a safe alternative location (such as external storage or cloud services). This ensures data integrity and business continuity if the primary storage medium fails or is compromised.

Marking scheme

1 mark: Identification of a valid utility program (e.g., Disk Defragmenter, Backup software, Disk Cleanup, Anti-virus/malware, File compression).
1 mark: Accurate explanation of how the first utility helps maintain the system.
1 mark: Identification of a second, distinct utility program.
1 mark: Accurate explanation of how the second utility helps maintain the system.
Question 3 · Recall & Description
4 marks
Computer networks use both Media Access Control (MAC) addresses and Internet Protocol (IP) addresses. Describe two key differences between a MAC address and an IP address.
Show answer & marking scheme

Worked solution

Key Difference 1: MAC addresses are physical and permanent; they are hard-coded into the Network Interface Card (NIC) at manufacture and cannot easily be altered. Conversely, IP addresses are logical and dynamic; they are allocated by a network router or DHCP server and change when a device connects to a different network.
Key Difference 2: MAC addresses operate at the Data Link Layer (Layer 2) of the OSI model to identify specific hardware within a local network segment. IP addresses operate at the Network Layer (Layer 3) to route packets globally across interconnected networks (like the Internet).

Marking scheme

1 mark: Explanation of physical/permanent nature of MAC vs logical/dynamic nature of IP.
1 mark: Detail/elaboration on assignment (MAC assigned by manufacturer vs IP assigned by DHCP/administrator).
1 mark: Explanation of local networking (MAC used in LAN) vs global routing (IP used in WAN/Internet).
1 mark: Detail/elaboration on format (MAC is 48-bit hex vs IP is typically 32-bit dotted-decimal or 128-bit hex).
Max 4 marks overall.
Question 4 · Recall & Description
4 marks
Sound must be converted into digital format before it can be processed by a computer. Describe how sound is sampled and digitized, referencing the terms 'sampling rate' and 'sampling resolution' in your answer.
Show answer & marking scheme

Worked solution

An analogue sound wave is continuous and must be converted into discrete digital values using an Analogue-to-Digital Converter (ADC). The ADC measures the amplitude of the analogue wave at fixed, regular intervals. The frequency of these measurements is called the sampling rate, measured in Hertz (Hz). Each captured amplitude value is then quantized and converted to a binary number using a fixed number of bits, which is determined by the sampling resolution (or bit depth). A higher sampling rate and resolution result in a more accurate digital representation of the sound wave.

Marking scheme

1 mark: Mentioning that continuous analogue sound is captured by an Analogue-to-Digital Converter (ADC).
1 mark: Describing sampling as taking measurements of the wave's amplitude at regular time intervals.
1 mark: Explaining 'sampling rate' as the number of sound samples taken per second (measured in Hz).
1 mark: Explaining 'sampling resolution' as the number of bits allocated to store each amplitude sample (determining precision).
Question 5 · Recall & Description
4 marks
Describe the differences between Open Source software and Shareware software licensing models.
Show answer & marking scheme

Worked solution

Open Source software license models mandate that the original source code is made freely available to the public. Users are legally permitted to study, alter, and redistribute the modified source code under the same licensing terms.
Shareware software is commercial, proprietary software that is distributed for free on a trial basis. After the trial period expires, users must purchase a license to continue using the software or unlock all features. The source code is kept secret (compiled) and users are not permitted to modify it.

Marking scheme

1 mark: Open source provides access to the source code for inspection and customization.
1 mark: Open source allows free redistribution and modification of the software under the same license terms.
1 mark: Shareware is distributed free of charge on a temporary trial or restricted feature set basis.
1 mark: Shareware is proprietary, meaning source code is not accessible, and payment is required for full/continued usage.
Question 6 · Technical Calculations & Logic Tables
5 marks
Convert the negative denary number \(-22.625\) into a 12-bit fixed-point binary representation using two's complement. You must use 8 bits for the integer part and 4 bits for the fractional part. Show your working.
Show answer & marking scheme

Worked solution

1. First, convert the positive denary number \(22.625\) to binary:
- The integer part \(22\) is \(00010110_2\) in 8 bits (since \(16 + 4 + 2 = 22\)).
- The fractional part \(0.625\) is \(1010_2\) in 4 bits (since \(0.5 + 0.125 = 0.625\)).
- Combined representation for \(+22.625\) is \(00010110.1010_2\).

2. To find the two's complement for \(-22.625\):
- Step 1: Invert all the bits (one's complement):
\(00010110.1010 \rightarrow 11101001.0101_2\)
- Step 2: Add 1 to the least significant bit (the \(2^{-4}\) position):
\(11101001.0101 + 0.0001 = 11101001.0110_2\)

3. The final 12-bit representation is \(11101001.0110\).

Marking scheme

- 1 mark: Correct 8-bit representation of the integer part \(22\) as \(00010110\).
- 1 mark: Correct 4-bit representation of the fractional part \(0.625\) as \(1010\).
- 1 mark: Evidence of finding the one's complement: \(11101001.0101\).
- 1 mark: Adding 1 to the least significant bit of the fractional part.
- 1 mark: Correct final answer \(11101001.0110\) (also accept without the binary point: \(111010010110\)).
Question 7 · Technical Calculations & Logic Tables
5 marks
A logic circuit has three inputs \(A\), \(B\), and \(C\), and an output \(X\). The Boolean expression for the output of this circuit is:

\(X = (A \text{ AND } B) \text{ OR } (\text{NOT } B \text{ AND } \text{NOT } C)\)

Complete the truth table below by determining the value of \(X\) for each row. Show your intermediate working for the terms \(P = A \text{ AND } B\) and \(Q = \text{NOT } B \text{ AND } \text{NOT } C\).

| A | B | C | P | Q | X |
|---|---|---|---|---|---|
| 0 | 0 | 0 | | | |
| 0 | 0 | 1 | | | |
| 0 | 1 | 0 | | | |
| 0 | 1 | 1 | | | |
| 1 | 0 | 0 | | | |
| 1 | 0 | 1 | | | |
| 1 | 1 | 0 | | | |
| 1 | 1 | 1 | | | |
Show answer & marking scheme

Worked solution

We calculate the intermediate columns first:
- \(P = A \text{ AND } B\): This is 1 only when both \(A\) and \(B\) are 1. It is 1 for the last two rows, and 0 for all other rows.
- \(Q = \text{NOT } B \text{ AND } \text{NOT } C\): This is 1 only when both \(B\) and \(C\) are 0. It is 1 for rows 1 and 5, and 0 for all other rows.
- \(X = P \text{ OR } Q\): This is 1 if either \(P\) or \(Q\) is 1.

Let's evaluate each row:
- Row 1 (0,0,0): \(P = 0\), \(Q = 1 \rightarrow X = 1\)
- Row 2 (0,0,1): \(P = 0\), \(Q = 0 \rightarrow X = 0\)
- Row 3 (0,1,0): \(P = 0\), \(Q = 0 \rightarrow X = 0\)
- Row 4 (0,1,1): \(P = 0\), \(Q = 0 \rightarrow X = 0\)
- Row 5 (1,0,0): \(P = 0\), \(Q = 1 \rightarrow X = 1\)
- Row 6 (1,0,1): \(P = 0\), \(Q = 0 \rightarrow X = 0\)
- Row 7 (1,1,0): \(P = 1\), \(Q = 0 \rightarrow X = 1\)
- Row 8 (1,1,1): \(P = 1\), \(Q = 0 \rightarrow X = 1\)

The final outputs for \(X\) are: 1, 0, 0, 0, 1, 0, 1, 1.

Marking scheme

- 1 mark: Correct values for intermediate column \(P = A \text{ AND } B\) (0, 0, 0, 0, 0, 0, 1, 1).
- 1 mark: Correct values for intermediate column \(Q = \text{NOT } B \text{ AND } \text{NOT } C\) (1, 0, 0, 0, 1, 0, 0, 0).
- 3 marks: Correct final values for column \(X\):
- 3 marks for all 8 rows correct (1, 0, 0, 0, 1, 0, 1, 1)
- 2 marks for 6 or 7 rows correct
- 1 mark for 4 or 5 rows correct
Question 8 · structured
6 marks
A library database uses two tables: MEMBER and LOAN.

The MEMBER table contains: MemberID, FirstName, LastName, DateOfBirth.
The LOAN table needs to store: LoanID, MemberID, BookTitle, LoanDate.

(a) Write a Data Definition Language (DDL) SQL script to create the LOAN table.
Ensure that:
- LoanID is the primary key (integer).
- MemberID is a foreign key referencing the MEMBER table.
- BookTitle is a text field of maximum 100 characters.
- LoanDate is a date field. [3]

(b) Write a Data Manipulation Language (DML) SQL query to retrieve the FirstName and LastName of all members who have borrowed books, along with the BookTitle and LoanDate of their loans.
The results must only show loans made from '2023-01-01' onwards and must be sorted in alphabetical order by the member's LastName. [3]
Show answer & marking scheme

Worked solution

(a) SQL script to create the table:
```sql
CREATE TABLE LOAN (
LoanID INT PRIMARY KEY,
MemberID VARCHAR(10),
BookTitle VARCHAR(100),
LoanDate DATE,
FOREIGN KEY (MemberID) REFERENCES MEMBER(MemberID)
);
```
(b) SQL query to fetch matching records:
```sql
SELECT MEMBER.FirstName, MEMBER.LastName, LOAN.BookTitle, LOAN.LoanDate
FROM MEMBER
INNER JOIN LOAN ON MEMBER.MemberID = LOAN.MemberID
WHERE LOAN.LoanDate >= '2023-01-01'
ORDER BY MEMBER.LastName ASC;
```

Marking scheme

(a) [Max 3 marks]:
- 1 mark: CREATE TABLE LOAN with correct attribute names and appropriate data types (e.g., INT/INTEGER for LoanID, DATE for LoanDate, VARCHAR(100) for BookTitle).
- 1 mark: Correctly designating LoanID as PRIMARY KEY.
- 1 mark: Correctly designating MemberID as FOREIGN KEY referencing MEMBER(MemberID).

(b) [Max 3 marks]:
- 1 mark: Correctly joining tables using INNER JOIN (or implicit join in FROM clause) matching on MemberID, and selecting FirstName, LastName, BookTitle, and LoanDate.
- 1 mark: Correct WHERE condition evaluating LoanDate >= '2023-01-01' (or > '2022-12-31').
- 1 mark: Correct ORDER BY clause on LastName (ascending/ASC or default).
Question 9 · structured
6 marks
A school's sports club database contains details of students and clubs.
- A student can join many clubs.
- A club can have many students.

(a) (i) Explain why this relationship cannot be directly implemented in a relational database. [1]
(a) (ii) State how this relationship is resolved. Write down the design schema for the third table (name it STUDENT_CLUB) using the format: TableName(Attribute1, Attribute2, ...) with primary keys underlined. [2]

(b) Write an SQL script to insert a new student record into an existing table named STUDENT.
The table has columns: StudentID (text), StudentName (text), and DateOfBirth (date).
The details to insert are:
- StudentID: 'S908'
- StudentName: 'Alice Green'
- DateOfBirth: '2008-05-14' [3]
Show answer & marking scheme

Worked solution

(a) (i) Relational databases do not support direct many-to-many (M:N) relationships because they lead to repeating groups, data redundancy, and anomalies.
(a) (ii) The relationship is resolved by creating an associative/link/junction table (STUDENT_CLUB) that forms two one-to-many relationships.
Schema: STUDENT_CLUB(underlineStudentID/underline, underlineClubID/underline, DateJoined) where StudentID and ClubID form the composite primary key.

(b) SQL script to insert a record:
```sql
INSERT INTO STUDENT (StudentID, StudentName, DateOfBirth)
VALUES ('S908', 'Alice Green', '2008-05-14');
```

Marking scheme

(a) (i) [Max 1 mark]:
- 1 mark: Explaining that many-to-many relationships cannot be directly modeled/implemented because they violate relational modeling rules/lead to redundancy/cannot support single-value cell integrity.

(a) (ii) [Max 2 marks]:
- 1 mark: Stating that a link/junction/associative table is created to break the relationship into two 1-to-many relationships.
- 1 mark: Correct schema notation with composite primary key (both fields underlined to indicate primary key, e.g., STUDENT_CLUB(StudentID, ClubID, ...)).

(b) [Max 3 marks]:
- 1 mark: Correct use of INSERT INTO STUDENT keyword.
- 1 mark: Correct order or mapping of columns (StudentID, StudentName, DateOfBirth).
- 1 mark: Correctly formatted VALUES with quotes around string and date values ('S908', 'Alice Green', '2008-05-14').

Paper 2 Fundamental Problem-solving and Programming Skills

Answer all questions. Complete all pseudocode scripts precisely.
8 Question · 63 marks
Question 1 · Pseudocode & Trace Tables
8 marks
An algorithm is designed to perform a run-length compression on an input string. Below is the pseudocode of the function `CompressString`:

```pseudocode
FUNCTION CompressString(Str : STRING) RETURNS STRING
DECLARE OutStr : STRING
DECLARE i, Count : INTEGER
DECLARE CurrentChar : CHAR

OutStr <-- ""
IF LENGTH(Str) > 0 THEN
CurrentChar <-- MID(Str, 1, 1)
Count <-- 1
FOR i <-- 2 TO LENGTH(Str)
IF MID(Str, i, 1) = CurrentChar THEN
Count <-- Count + 1
ELSE
OutStr <-- OutStr + CurrentChar + NUM_TO_STR(Count)
CurrentChar <-- MID(Str, i, 1)
Count <-- 1
ENDIF
NEXT i
OutStr <-- OutStr + CurrentChar + NUM_TO_STR(Count)
ENDIF
RETURN OutStr
ENDFUNCTION
```

Complete the trace table below for the function call `CompressString("XXYZZZ")`.
Show answer & marking scheme

Worked solution

We trace the function step-by-step:
1. `Str` is initialized to `"XXYZZZ"`. `OutStr` is `""`.
2. `LENGTH(Str)` is 6, so we enter the conditional block.
3. `CurrentChar` is assigned `MID(Str, 1, 1)`, which is `"X"`. `Count` is initialized to 1.
4. Loop `i` goes from 2 to 6:
- `i = 2`: `MID(Str, 2, 1)` is `"X"`. Matches `CurrentChar`. `Count` becomes 2.
- `i = 3`: `MID(Str, 3, 1)` is `"Y"`. Mismatch! `OutStr` becomes `"" + "X" + "2"` = `"X2"`. `CurrentChar` becomes `"Y"`. `Count` is reset to 1.
- `i = 4`: `MID(Str, 4, 1)` is `"Z"`. Mismatch! `OutStr` becomes `"X2" + "Y" + "1"` = `"X2Y1"`. `CurrentChar` becomes `"Z"`. `Count` is reset to 1.
- `i = 5`: `MID(Str, 5, 1)` is `"Z"`. Matches `CurrentChar`. `Count` becomes 2.
- `i = 6`: `MID(Str, 6, 1)` is `"Z"`. Matches `CurrentChar`. `Count` becomes 3.
5. Loop terminates.
6. Outside the loop, `OutStr` is updated: `"X2Y1" + "Z" + "3"` = `"X2Y1Z3"`.
7. The function returns `"X2Y1Z3"`.

Marking scheme

- 1 mark: Correctly setting initial values (`OutStr` = "", `CurrentChar` = "X", `Count` = 1).
- 1 mark: Correctly writing the loop variable `i` tracking from 2 to 6.
- 2 marks: Correct logic on duplicate matches (updating `Count` to 2 at `i=2`, to 2 at `i=5`, and to 3 at `i=6`).
- 2 marks: Correct transition on mismatch (updating `OutStr` to "X2" and "X2Y1", resetting `Count` to 1, and updating `CurrentChar` at `i=3` and `i=4`).
- 1 mark: Correct final concatenation of `OutStr` after the loop terminates ("X2Y1Z3").
- 1 mark: Correct final returned value shown in the table ("X2Y1Z3").
Question 2 · Pseudocode & Trace Tables
8 marks
The procedure `CompactArray` is designed to process an array of integers `DataList` containing `NumElements` elements. It moves all non-negative elements to the beginning of the array while preserving their original order, and sets all remaining trailing elements to `0`.

Complete the following pseudocode by writing the correct expressions for **Gap A**, **Gap B**, **Gap C**, and **Gap D**.

```pseudocode
PROCEDURE CompactArray(BYREF DataList : ARRAY OF INTEGER, NumElements : INTEGER)
DECLARE WritePos, i : INTEGER
WritePos <-- 1
FOR i <-- 1 TO NumElements
IF DataList[i] >= 0 THEN
IF i <> WritePos THEN
DataList[WritePos] <-- [ Gap A ]
ENDIF
WritePos <-- [ Gap B ]
ENDIF
NEXT i

FOR i <-- [ Gap C ] TO NumElements
DataList[i] <-- [ Gap D ]
NEXT i
ENDPROCEDURE
```
Show answer & marking scheme

Worked solution

1. **Gap A**: Inside the condition where a non-negative number is found, if the iterator `i` is different from the target writing position `WritePos`, we must copy the current element to the non-negative sequence. Therefore, `DataList[WritePos]` is updated with `DataList[i]`.
2. **Gap B**: Once a non-negative number is kept or moved, we increment our tracking pointer `WritePos` to prepare for the next valid non-negative number. Thus, `WritePos <-- WritePos + 1`.
3. **Gap C**: After the array has been compacted up to index `WritePos - 1`, the remaining items from `WritePos` up to `NumElements` must be padded with zero. Thus, the loop to clean the array starts at `WritePos`.
4. **Gap D**: The task is to set remaining cells to zero. Therefore, `DataList[i] <-- 0`.

Marking scheme

- Gap A: 2 marks for `DataList[i]` (accept with spacing variation).
- Gap B: 2 marks for `WritePos + 1` (accept with spacing variation).
- Gap C: 2 marks for `WritePos`.
- Gap D: 2 marks for `0` (or `0` as integer constant).
Question 3 · Pseudocode & Trace Tables
8 marks
The function `CountPattern` checks how many times a two-character `Pattern` appears in a given string `Text`. The character `'?'` in `Pattern` serves as a wildcard that matches any character.

```pseudocode
FUNCTION CountPattern(Text : STRING, Pattern : STRING) RETURNS INTEGER
DECLARE Count, i, TextLen : INTEGER
DECLARE Match : BOOLEAN
DECLARE Char1, Char2, P1, P2 : CHAR

Count <-- 0
TextLen <-- LENGTH(Text)
IF TextLen < 2 THEN
RETURN 0
ENDIF

P1 <-- MID(Pattern, 1, 1)
P2 <-- MID(Pattern, 2, 1)

FOR i <-- 1 TO TextLen - 1
Char1 <-- MID(Text, i, 1)
Char2 <-- MID(Text, i + 1, 1)
Match <-- FALSE

IF (P1 = "?" OR P1 = Char1) AND (P2 = "?" OR P2 = Char2) THEN
Match <-- TRUE
ENDIF

IF Match = TRUE THEN
Count <-- Count + 1
ENDIF
NEXT i

RETURN Count
ENDFUNCTION
```

Complete a dry run trace table for the function call: `CountPattern("ANANA", "?A")`.
Show answer & marking scheme

Worked solution

Step-by-step trace:
- **Initialization**:
- `Text` = `"ANANA"`, `Pattern` = `"?A"`
- `Count` = 0
- `TextLen` = 5
- `P1` = `"?"`
- `P2` = `"A"`
- **Loop i = 1**:
- `Char1` = `"A"`, `Char2` = `"N"`
- `Match` condition: `(P1 = "?" OR P1 = "A")` is TRUE; `(P2 = "?" OR P2 = "N")` is FALSE (since "A" != "N").
- `Match` remains `FALSE`. `Count` remains 0.
- **Loop i = 2**:
- `Char1` = `"N"`, `Char2` = `"A"`
- `Match` condition: `(P1 = "?" OR P1 = "N")` is TRUE; `(P2 = "?" OR P2 = "A")` is TRUE.
- `Match` becomes `TRUE`. `Count` becomes 1.
- **Loop i = 3**:
- `Char1` = `"A"`, `Char2` = `"N"`
- `Match` condition: `(P1 = "?" OR P1 = "A")` is TRUE; `(P2 = "?" OR P2 = "N")` is FALSE.
- `Match` becomes `FALSE`. `Count` remains 1.
- **Loop i = 4**:
- `Char1` = `"N"`, `Char2` = `"A"`
- `Match` condition: `(P1 = "?" OR P1 = "N")` is TRUE; `(P2 = "?" OR P2 = "A")` is TRUE.
- `Match` becomes `TRUE`. `Count` becomes 2.
- **Loop terminates** (i goes up to `TextLen - 1` which is 4).
- **Output**: Returns `Count` (2).

Marking scheme

- 1 mark: Correctly setting initial values (`Count` = 0, `P1` = "?", `P2` = "A").
- 2 marks: Correct execution tracking of loop variable `i` (1 to 4) and corresponding correct evaluation of `Char1` and `Char2` in each iteration.
- 2 marks: Correct tracking of the Boolean `Match` variable (FALSE, TRUE, FALSE, TRUE).
- 2 marks: Correct tracking of the variable `Count` (increments to 1 at `i=2`, increments to 2 at `i=4`).
- 1 mark: Correct final output/returned value of 2.
Question 4 · Algorithm Refinement & Stepwise Logic
6 marks
A software developer is designing a temperature-monitoring algorithm for a greenhouse. The program processes hourly temperature measurements stored in a 1D array.

The developer has defined the following high-level design:
1. Initialize variables.
2. Input 24 temperature readings into a 1D array TempReadings (indices 1 to 24).
3. Count how many separate 'anomalous periods' occur. An anomalous period is defined as a continuous sequence of 3 or more hourly readings that are strictly greater than a defined threshold value.
4. Output the total number of anomalous periods.

Refine Step 3 of this algorithm by writing structured pseudocode. You must use the following variables:
- TempReadings : 1D array [1:24] of REAL
- Threshold : REAL (already contains the threshold value)
- AnomalyCount : INTEGER (to store the total count of anomalous periods)
- ConsecutiveCount : INTEGER (to count the current consecutive readings exceeding the threshold)
Show answer & marking scheme

Worked solution

The algorithm needs to identify continuous runs of values above the threshold. We maintain a counter `ConsecutiveCount` which tracks the length of the current run of readings above `Threshold`. When a reading does not exceed the threshold, `ConsecutiveCount` must be reset to 0.

To ensure we only increment `AnomalyCount` once per run (when it first qualifies as an anomaly at length 3), we perform the check `IF ConsecutiveCount = 3 THEN AnomalyCount <- AnomalyCount + 1`. This prevents longer sequences (e.g., 4 or 5 consecutive readings) from incorrectly registering as multiple anomalous periods.

An alternative approach of tracking when a sequence starts and ends is also valid, but the conditional count-reset approach is the most elegant refinement.

Marking scheme

- 1 mark: Initializing both AnomalyCount and ConsecutiveCount to 0.
- 1 mark: Correct loop header (e.g., FOR Index <- 1 TO 24) to iterate through all 24 elements.
- 1 mark: Correct comparison checking if TempReadings[Index] > Threshold inside the loop.
- 1 mark: Incrementing ConsecutiveCount when true, and resetting ConsecutiveCount <- 0 in an ELSE branch.
- 1 mark: Correctly checking if ConsecutiveCount = 3 to increment AnomalyCount exactly once per period.
- 1 mark: Correctly closing control structures with ENDIF and ENDFOR.
Question 5 · Algorithm Refinement & Stepwise Logic
6 marks
A system validates product serial codes. A valid serial code must follow the exact pattern LL-NNN-LL, where L represents an uppercase letter ('A' to 'Z') and N represents a single digit ('0' to '9').

The programmer has written the outer structure of the validation logic below:

```
IsValid <- TRUE
IF LENGTH(SerialCode) <> 9 THEN
IsValid <- FALSE
ELSE
IF MID(SerialCode, 3, 1) <> "-" OR MID(SerialCode, 7, 1) <> "-" THEN
IsValid <- FALSE
ELSE
// Write refined logic for steps 4 and 5 here
ENDIF
ENDIF
```

Write the refined pseudocode for the inner block to complete steps 4 and 5 of the validation design:
- Step 4: Validate that characters at positions 1, 2, 8, and 9 are uppercase letters.
- Step 5: Validate that characters at positions 4, 5, and 6 are digits.
Show answer & marking scheme

Worked solution

To refine Steps 4 and 5, we extract each character at the specified index positions using the `MID` function.
For positions 1, 2, 8, and 9, we check if the extracted character falls outside the range 'A' to 'Z'. If it does, we set our boolean flag `IsValid` to `FALSE`.
Similarly, for positions 4, 5, and 6, we check if the extracted character falls outside the range '0' to '9', setting `IsValid` to `FALSE` if it does.
Loops are used here for code efficiency, though individual character lookups (e.g., checking index 1, 2, 8, 9, 4, 5, 6 explicitly) are also logic-equivalent solutions.

Marking scheme

- 1 mark: Correctly extracting single characters using the MID function, e.g., MID(SerialCode, Index, 1).
- 1 mark: Range-checking letters correctly (either checking for < 'A' OR > 'Z' to invalidate, or checking >= 'A' AND <= 'Z' to confirm).
- 1 mark: Range-checking digits correctly (either checking for < '0' OR > '9' to invalidate, or checking >= '0' AND <= '9' to confirm).
- 1 mark: Correctly targeting positions 1, 2, 8, and 9 for letter validation.
- 1 mark: Correctly targeting positions 4, 5, and 6 for digit validation.
- 1 mark: Setting IsValid <- FALSE when validation fails, without accidentally resetting it to TRUE if a later character succeeds.
Question 6 · File Operations & Protocol Design
9 marks
A text file, `DeviceLogs.txt`, contains structured communication logs from multiple remote sensors. Each line in the file is exactly 16 characters long and formatted according to a strict system protocol:
- Characters 1 to 6: Sensor ID (e.g., `SENS01`)
- Character 7: A comma (`,`)
- Characters 8 to 10: Status code (`ERR` or `OK ` with a trailing space)
- Character 11: A colon (`:`)
- Characters 12 to 16: Numerical data reading as a decimal string (e.g., `045.5`)

Write a pseudocode procedure `ExtractErrors` that processes `DeviceLogs.txt` and performs the following tasks:
1. Reads each line from `DeviceLogs.txt` until the end of the file is reached.
2. Extracts the Sensor ID, Status code, and Numerical reading using standard pseudocode string functions.
3. Checks if the Status code is `"ERR"` and the Numerical reading is strictly greater than `50.0`.
4. For each matching entry, writes a line to a new text file, `CriticalErrors.txt`, in the format:
`[Sensor ID] VALUE [Numerical reading]` (for example: `SENS01 VALUE 062.4`)
5. Ensures both files are properly opened and closed.
Show answer & marking scheme

Worked solution

The procedure starts by opening the input file `DeviceLogs.txt` in `READ` mode and the output file `CriticalErrors.txt` in `WRITE` mode.
A loop continues to execute until the end of `DeviceLogs.txt` is detected using `EOF()`. Inside the loop, `READFILE` extracts a line. Using the `MID` function, substrings are sliced at the precise indices defined by the protocol format:
- `SensorID` is extracted from positions 1 to 6.
- `Status` is extracted from positions 8 to 10.
- `ValueStr` is extracted from positions 12 to 16.
The numeric string is cast to a REAL data type using `STR_TO_REAL` to allow numerical comparison. If the condition `Status = "ERR" AND ValueReal > 50.0` is met, a formatted string combining the ID and value is written to `CriticalErrors.txt`. Finally, both files are closed securely to release resource locks.

Marking scheme

Total Marks: 9
- 1 mark: Correct procedure header and declaration of required variables.
- 1 mark: Correctly opening both files with correct modes (READ and WRITE).
- 1 mark: Correct execution of `WHILE NOT EOF` loop on input file.
- 1 mark: Reading from file into a variable inside the loop.
- 1 mark: Correctly extracting Sensor ID (MID indices 1, 6) and Status (MID indices 8, 3).
- 1 mark: Correctly extracting and converting the numerical value string to a REAL type.
- 1 mark: Correct logic comparison for both status (`"ERR"`) and value range (`> 50.0`).
- 1 mark: Correctly assembling the output string and writing to `CriticalErrors.txt`.
- 1 mark: Closing both files properly at the end of execution.
Question 7 · File Operations & Protocol Design
9 marks
An embedded telemetry logger processes individual data packets before saving them to external storage.

1. Define a user-defined composite record structure named `Packet` with the following field attributes:
- `DeviceID` (String)
- `Timestamp` (Integer)
- `Reading` (Real)

2. Write a pseudocode function `SerializePacket(Data : Packet) RETURNS String` that formats a `Packet` record into a single string formatted with a custom protocol separator hash (`#`). For example, a packet with `DeviceID` "DEV01", `Timestamp` 1609459200, and `Reading` 12.8 should be converted to: `"DEV01#1609459200#12.8"`.

3. Write a pseudocode procedure `SavePackets(Filename : String, PacketArray : ARRAY[1:100] OF Packet, Total : Integer)` that opens the specified file in `WRITE` mode, serializes and writes all valid packets from index 1 up to `Total` (inclusive) to the file, and then closes the file.
Show answer & marking scheme

Worked solution

The structure `Packet` is created using the `TYPE ... ENDTYPE` construct with the appropriate fields.

The `SerializePacket` function receives a single parameter of type `Packet`. It converts the non-string attributes (`Timestamp` and `Reading`) into string types using the standard built-in casting functions `NUM_TO_STR()` and `REAL_TO_STR()`, concatenates them using the delimiter character `"#"`, and returns the constructed string.

The `SavePackets` procedure opens a file matching the parameter `Filename` in write mode, runs a loop bounded from `1` to `Total`, calls the serialization helper on each indexed array element, writes each returned string as a new line in the file, and closes the file safely.

Marking scheme

Total Marks: 9
- 2 marks: Correct declaration of user-defined type `Packet` including matching field types.
- 1 mark: Correct header and return type definition for `SerializePacket`.
- 1 mark: Correct type casting of numerical fields inside `SerializePacket`.
- 1 mark: Correct concatenation using the `#` symbol in the returned string.
- 1 mark: Correct header for `SavePackets` with complete parameter specifications.
- 1 mark: Correctly opening/closing files inside `SavePackets`.
- 1 mark: Correct `FOR` loop boundary iterating from 1 to `Total`.
- 1 mark: Correctly calling `SerializePacket` and writing the result to the file.
Question 8 · File Operations & Protocol Design
9 marks
A banking validation system updates temporary balances in-memory from daily transactional log files.
An existing text file, `Balances.txt`, contains active bank balances. Each line has a fixed layout: a 5-character account number, followed by a space, followed by a real balance stored as a string.

Another file, `Transactions.txt`, contains operations to process. Each line represents a record in this format:
- Character 1: Operation type (`'D'` for Deposit, `'W'` for Withdrawal)
- Character 2: Space
- Characters 3 to 7: Account number (5 characters)
- Character 8: Space
- Characters 9 onwards: Transaction amount as a decimal string

There are exactly 50 balances in `Balances.txt`. Write a pseudocode procedure `ProcessTransactions` to:
1. Initialize a 1D array of records named `AccountList` size `[1:50]` where each index holds an `AccountRecord` (containing fields `AccNum : STRING` and `Balance : REAL`).
2. Read `Balances.txt` to load these 50 entries into the array, and close the file.
3. Read through all transaction logs in `Transactions.txt` line by line until EOF. For each log, search `AccountList` for the matching account number. If found, update the balance by adding (for `'D'`) or subtracting (for `'W'`) the transaction amount.
4. Write the finalized data from `AccountList` back to a new file named `UpdatedBalances.txt` in the same structure as `Balances.txt`, and close all files.
Show answer & marking scheme

Worked solution

The application is split into three phases:
1. Loading: We declare a record layout `AccountRecord` and dimension an array of size 50. The loop reads exactly 50 lines from `Balances.txt`, dividing characters based on positional boundaries: `AccNum` represents indices 1 to 5, and the balance string starts at index 7. This is converted to a REAL type and stored inside `AccountList`.
2. Processing: `Transactions.txt` is read line-by-line using a `WHILE NOT EOF` loop. String functions are used to extract operations: index 1 is the action character (`'D'`/`'W'`), indices 3-7 identify the target account, and everything from index 9 to the end is converted into a REAL transaction value. A linear search checks the matching element inside `AccountList`. Once matched, the corresponding transaction logic modifies the record balance.
3. Outputting: A simple loop walks through the array, constructs a string separated by a space, writes each line, and safely closes the file stream.

Marking scheme

Total Marks: 9
- 1 mark: Defining `AccountRecord` structure correctly with fields `AccNum` and `Balance`.
- 1 mark: Reading from `Balances.txt` 50 times and successfully populating `AccountList` array.
- 1 mark: Extracting components correctly from `Balances.txt` using indexing / length calculation.
- 1 mark: Correctly setting up loop to process `Transactions.txt` until EOF.
- 1 mark: Correct extraction of transaction attributes (operation type, account ID, value) using string slice positions.
- 1 mark: Implementing sequential search pattern to identify matching accounts inside the array.
- 1 mark: Correct application of arithmetic addition for `'D'` and subtraction for `'W'` modifications.
- 1 mark: Opening and loop writing updated memory contents back into `UpdatedBalances.txt`.
- 1 mark: Ensuring all files accessed throughout are securely closed (`Balances.txt`, `Transactions.txt`, `UpdatedBalances.txt`).

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? Practice unlimited on Thinka — instant answers included.

Start Practising Free