Cambridge IAS-Level · Thinka-original Practice Paper

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

Thinka Nov 2024 (V3) Cambridge International A Level-Style Mock — Computer Science (9618)

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

Paper 13 (Theory Fundamentals)

Answer all questions. Calculators must not be used.
16 Question · 74.79999999999998 marks
Question 1 · Short Answer Theory
2.5 marks
Explain why the UTF-8 encoding scheme is often preferred over standard ASCII, and how UTF-8 remains backward compatible with standard ASCII.
Show answer & marking scheme

Worked solution

1. Why preferred: UTF-8 supports over a million characters (Unicode), allowing representation of global languages, symbols, and emojis, whereas standard ASCII only supports 128 characters. 2. Backward compatibility: Standard ASCII characters (0 to 127) are encoded in UTF-8 as a single byte starting with a '0' bit followed by the 7-bit ASCII code. This means any valid ASCII file is also a valid UTF-8 file.

Marking scheme

1.0 mark: Explanation of UTF-8's larger character set capacity compared to standard ASCII's 128-character limit. 1.0 mark: Explanation of backward compatibility (first 128 characters use the exact same binary representations). 0.5 marks: Detail that a standard ASCII file is directly readable as a valid UTF-8 file without conversion.
Question 2 · Short Answer Theory
2.5 marks
In the context of web technologies, state the primary difference between client-side scripting and server-side scripting. Provide one typical example of a task performed by each.
Show answer & marking scheme

Worked solution

Client-side scripting (such as JavaScript) is executed directly on the client machine's web browser. Server-side scripting (such as PHP, Python, or ASP.NET) runs on the remote web server. Client-side examples: real-time input validation, responsive interface animations. Server-side examples: user authentication, querying databases, session management.

Marking scheme

1.0 mark: Distinguishing where execution occurs (browser/local vs web server). 0.75 marks: Valid example of client-side task (e.g., input format check, UI interaction). 0.75 marks: Valid example of server-side task (e.g., database connection, authentication).
Question 3 · Short Answer Theory
2.5 marks
During the fetch stage of the Fetch-Execute cycle, instructions are retrieved from main memory. Write the Register Transfer Notation (RTN) steps for the fetch stage, starting from the point where the address of the next instruction is ready in the Program Counter (PC).
Show answer & marking scheme

Worked solution

The register transfer steps during the fetch stage are: 1. Copy the address from the Program Counter (PC) to the Memory Address Register (MAR): MAR <- [PC]. 2. Increment the Program Counter: PC <- [PC] + 1. 3. Copy the instruction stored at the address in MAR to the Memory Data Register (MDR): MDR <- [[MAR]]. 4. Copy the instruction from MDR to the Current Instruction Register (CIR): CIR <- [MDR].

Marking scheme

0.5 marks: MAR <- [PC]. 0.5 marks: PC <- [PC] + 1. 0.75 marks: MDR <- [[MAR]] (accept MDR <- [Memory]). 0.75 marks: CIR <- [MDR].
Question 4 · Short Answer Theory
2.5 marks
An operating system can link library routines to an executable program either statically or dynamically. Explain one benefit and one drawback of using Dynamic Link Libraries (DLLs) instead of static linking.
Show answer & marking scheme

Worked solution

Dynamic Link Libraries (DLLs) are linked at runtime. Benefit: Memory and disk space efficiency: only one copy of the library is kept in memory to be shared among multiple applications. Also, libraries can be updated without recompiling the applications. Drawback: Dependency issues ('DLL hell'): if a DLL is deleted, corrupted, or replaced by an incompatible version, any application relying on it may crash or fail to open.

Marking scheme

1.25 marks: Clear benefit (e.g., memory/disk space savings or independent updates). 1.25 marks: Clear drawback (e.g., dependency issues, broken links, or minor runtime linking overhead).
Question 5 · Short Answer Theory
2.5 marks
Computer systems must maintain both data integrity and data privacy. Describe the difference between data integrity and data privacy, and identify one threat to each.
Show answer & marking scheme

Worked solution

Data integrity is about the correctness, accuracy, and completeness of data. Data privacy is about controlling who has access to that data to prevent unauthorized exposure. Threat to integrity: transmission noise, storage medium degradation, malicious alteration. Threat to privacy: spyware, unauthorized hacking, physical theft of storage media.

Marking scheme

1.0 mark: Distinction between integrity (accuracy/completeness) and privacy (protection against unauthorized access). 0.75 marks: Valid threat to integrity. 0.75 marks: Valid threat to privacy.
Question 6 · Short Answer Theory
2.5 marks
In a relational database, explain the concept of referential integrity and describe how it is enforced using foreign keys.
Show answer & marking scheme

Worked solution

Referential integrity ensures that relationships between tables remain consistent. A foreign key in a child table must reference a valid primary key in a parent table. The database management system enforces this by: 1. Rejecting modifications/deletions of primary keys in the parent table if corresponding foreign keys exist (unless cascading is configured). 2. Rejecting the insertion of records in the child table that reference a non-existent primary key.

Marking scheme

1.0 mark: Definition of referential integrity (maintaining consistency between tables so no orphaned records exist). 1.0 mark: Role of foreign keys (matching primary keys of the parent table). 0.5 marks: How DBMS enforces it (blocking illegal deletions/insertions).
Question 7 · Short Answer Theory
2.5 marks
Structure charts are used in top-down design to show the decomposition of a problem. Describe the purpose of: 1. A parameter passing indicator (couple) with an open circle. 2. A parameter passing indicator (couple) with a filled circle.
Show answer & marking scheme

Worked solution

Structure charts use couples to show how modules communicate. 1. Data couple (open circle arrow): used to pass data parameters between modules for processing. 2. Control couple (filled circle arrow): used to pass flags/control signals that tell another module what action to take or indicate a status condition.

Marking scheme

1.25 marks: Accurate description of data couple (open circle) as passing data values. 1.25 marks: Accurate description of control couple/flag (filled circle) as passing control/status signals.
Question 8 · Short Answer Theory
2.5 marks
Software can be distributed under various licensing models. Explain the difference between Open Source software and Shareware in terms of source code availability and usage rights.
Show answer & marking scheme

Worked solution

Open Source software makes its source code publicly available, allowing users to adapt, inspect, and distribute their own modified versions. It is typically free. Shareware is closed-source software distributed without charge for a limited evaluation period or with restricted features, after which the user must purchase a license to continue using it.

Marking scheme

1.25 marks: Explanation of Open Source (source code available, modification and redistribution rights). 1.25 marks: Explanation of Shareware (no source code, trial-based distribution, payment required for continued/full use).
Question 9 · Short Answer
3 marks
Describe how a resistive touchscreen detects the position of a user's touch.
Show answer & marking scheme

Worked solution

A resistive touchscreen consists of two thin, flexible conductive/resistive layers separated by a small gap or insulating spacers. When a user applies pressure to the screen, the flexible outer layer bends and makes physical contact with the bottom layer. This contact completes an electrical circuit, causing a change in the electrical resistance/current at that point. A microprocessor or screen controller detects this change in voltage and calculates the precise X and Y coordinates of the touch point.

Marking scheme

Award up to 3 marks.
- 1 mark: Mentions that the screen consists of two conductive/resistive layers separated by a gap/spacers.
- 1 mark: Explains that pressure causes the outer layer to bend and touch/make contact with the inner layer.
- 1 mark: Explains that this physical contact completes an electrical circuit / changes the electrical resistance/current.
- 1 mark: Explains that a microprocessor/controller measures the change in voltage to calculate the coordinates (X and Y) of the touch.
Question 10 · Short Answer
2 marks
State two functions performed by a router when managing data transmission across networks.
Show answer & marking scheme

Worked solution

A router performs several vital roles when managing network traffic:
1. It reads the destination IP address of incoming data packets to determine where they need to go.
2. It maintains and references a routing table to identify the most efficient path/route for the packet.
3. It forwards packets of data from one network to another (e.g., from a LAN to a WAN) towards their final destination.
4. It can translate protocols between different networks.

Marking scheme

Award 1 mark per valid function described (maximum of 2 marks):
- Inspects/reads the destination IP address of incoming data packets.
- Maintains/references a routing table to determine the most efficient route/path.
- Forwards data packets to the next node/router/destination.
- Connects different networks together (e.g., LAN to WAN / local network to the Internet).
- Translates protocols between different networks.
Question 11 · Structured Design / SQL / Trace
8.3 marks
A school library database stores data using two tables:
`Book(BookID, Title, Author, Genre, YearPublished)`
`Loan(LoanID, BookID, MemberID, DateBorrowed, Returned)`

(a) Write a SQL query to display the `Title` and `Author` of all books where the `Genre` is 'Sci-Fi' and the `YearPublished` is after 2015. The results must be sorted alphabetically by `Title`. [4 marks]

(b) Write a SQL query to count and display the total number of loans that have not yet been returned (the field `Returned` contains the boolean value `FALSE` for outstanding loans). Change the header of the resulting count column to `OutstandingLoans`. [4.3 marks]
Show answer & marking scheme

Worked solution

Part (a):
The query retrieves specific fields from the `Book` table under multiple conditions.
1. Target columns: `Title`, `Author`.
2. Table: `Book`.
3. Filter criteria: `Genre = 'Sci-Fi'` AND `YearPublished > 2015`.
4. Ordering: `ORDER BY Title` (the default order is ascending, so `ASC` is optional but acceptable).

SQL Code:
```sql
SELECT Title, Author
FROM Book
WHERE Genre = 'Sci-Fi' AND YearPublished > 2015
ORDER BY Title;
```

Part (b):
We need to calculate the sum total of records that match our criteria.
1. Aggregate function: `COUNT(LoanID)` or `COUNT(*)`.
2. Column alias: `AS OutstandingLoans`.
3. Table: `Loan`.
4. Filter condition: `Returned = FALSE`.

SQL Code:
```sql
SELECT COUNT(LoanID) AS OutstandingLoans
FROM Loan
WHERE Returned = FALSE;
```

Marking scheme

Part (a) [4 marks]:
- 1 mark: `SELECT Title, Author`
- 1 mark: `FROM Book`
- 1 mark: `WHERE Genre = 'Sci-Fi' AND YearPublished > 2015` (accept quotes around the numeric value if treated as string, but numeric comparison without quotes is standard)
- 1 mark: `ORDER BY Title` (or `ORDER BY Title ASC`)

Part (b) [4.3 marks]:
- 1.5 marks: `SELECT COUNT(LoanID)` or `SELECT COUNT(*)`
- 1.3 marks: `AS OutstandingLoans` (accept double or single quotes around alias, or no quotes)
- 1.5 marks: `FROM Loan WHERE Returned = FALSE` (accept `Returned = 0` or `NOT Returned` depending on syntax)
Question 12 · Structured Design / SQL / Trace
8.3 marks
Consider the following pseudocode algorithm that operates on a 1D array of integers:

```
DECLARE Values : ARRAY[1..6] OF INTEGER
DECLARE i, Temp, Count : INTEGER
Values[1] <-- 12
Values[2] <-- 5
Values[3] <-- 18
Values[4] <-- 9
Values[5] <-- 15
Values[6] <-- 3
Count <-- 0
FOR i <-- 1 TO 5
IF Values[i] > Values[i+1] THEN
Temp <-- Values[i]
Values[i] <-- Values[i+1]
Values[i+1] <-- Temp
Count <-- Count + 1
ENDIF
NEXT i
```

Complete the trace table below to show how variables change during the execution of this algorithm. Draw a line in a cell to indicate no change in value.
Show answer & marking scheme

Worked solution

Let's trace each iteration of the loop from `i = 1` to `5`:
- **Initial setup**: `Values` holds `[12, 5, 18, 9, 15, 3]`, `Count` is `0`.
- **i = 1**: Compares `Values[1]` (12) with `Values[2]` (5). Since `12 > 5` is true, the swap executes:
- `Temp` becomes `12`.
- `Values[1]` becomes `5`.
- `Values[2]` becomes `12`.
- `Count` increases to `1`.
- Current `Values` state: `[5, 12, 18, 9, 15, 3]`.
- **i = 2**: Compares `Values[2]` (12) with `Values[3]` (18). Since `12 > 18` is false, no swap occurs.
- **i = 3**: Compares `Values[3]` (18) with `Values[4]` (9). Since `18 > 9` is true, the swap executes:
- `Temp` becomes `18`.
- `Values[3]` becomes `9`.
- `Values[4]` becomes `18`.
- `Count` increases to `2`.
- Current `Values` state: `[5, 12, 9, 18, 15, 3]`.
- **i = 4**: Compares `Values[4]` (18) with `Values[5]` (15). Since `18 > 15` is true, the swap executes:
- `Temp` becomes `18`.
- `Values[4]` becomes `15`.
- `Values[5]` becomes `18`.
- `Count` increases to `3`.
- Current `Values` state: `[5, 12, 9, 15, 18, 3]`.
- **i = 5**: Compares `Values[5]` (18) with `Values[6]` (3). Since `18 > 3` is true, the swap executes:
- `Temp` becomes `18`.
- `Values[5]` becomes `3`.
- `Values[6]` becomes `18`.
- `Count` increases to `4`.
- Final `Values` state: `[5, 12, 9, 15, 3, 18]`.

Marking scheme

Total 8.3 marks:
- 1 mark: Correct initial state (Count = 0).
- 1.5 marks: For the correct update at i=1 (Values[1]=5, Values[2]=12, Temp=12, Count=1).
- 1 mark: Recognizing i=2 results in no variable changes.
- 1.6 marks: For correct updates at i=3 (Values[3]=9, Values[4]=18, Temp=18, Count=2).
- 1.6 marks: For correct updates at i=4 (Values[4]=15, Values[5]=18, Temp=18, Count=3).
- 1.6 marks: For correct updates at i=5 (Values[5]=3, Values[6]=18, Temp=18, Count=4).
Question 13 · Structured Design / SQL / Trace
8.3 marks
A relational database table `Flight` is to be created. It contains information about scheduled airline flights. The details of the fields are:
- `FlightID`: alphanumeric string of exactly 6 characters, uniquely identifies each flight.
- `Origin`: alphabetic string of exactly 3 characters, representing the departure airport. This cannot be null.
- `Destination`: alphabetic string of exactly 3 characters, representing the arrival airport. This cannot be null.
- `DepartureTime`: time of departure.
- `Capacity`: integer representing total available seats.
- `AircraftID`: integer linking each flight to an aircraft.

(a) Write a SQL script to define and create the `Flight` table. Ensure that all primary key and foreign key constraints are correctly defined, assuming the parent table `Aircraft` already exists with a primary key `AircraftID`. [5.3 marks]

(b) State the role of:
(i) A Primary Key. [1.5 marks]
(ii) A Foreign Key. [1.5 marks]
Show answer & marking scheme

Worked solution

Part (a):
The script requires a standard Data Definition Language (DDL) format:
```sql
CREATE TABLE Flight (
FlightID CHAR(6) PRIMARY KEY,
Origin CHAR(3) NOT NULL,
Destination CHAR(3) NOT NULL,
DepartureTime TIME,
Capacity INT,
AircraftID INT,
FOREIGN KEY (AircraftID) REFERENCES Aircraft(AircraftID)
);
```
Note: `CHAR(3)` is preferred over `VARCHAR(3)` for fixed-length strings like 3-letter airport codes.

Part (b):
- (i) **Primary Key**: Ensures entity integrity by guaranteeing that every record in the table has a unique identifier and no key value is left null.
- (ii) **Foreign Key**: Restricts values in the child table to only those that exist in the referenced parent table, thereby enforcing referential integrity.

Marking scheme

Part (a) [5.3 marks]:
- 1 mark: `CREATE TABLE Flight (...)`
- 1 mark: `FlightID CHAR(6) PRIMARY KEY` (or `PRIMARY KEY (FlightID)` at bottom)
- 1 mark: `Origin CHAR(3) NOT NULL` and `Destination CHAR(3) NOT NULL` (accept `VARCHAR`)
- 1 mark: Appropriate types for other columns (`TIME` for DepartureTime, `INT`/`INTEGER` for Capacity and AircraftID)
- 1.3 marks: Correct foreign key syntax: `FOREIGN KEY (AircraftID) REFERENCES Aircraft(AircraftID)`

Part (b) [3 marks]:
- 1.5 marks: Correct explanation of primary key (uniquely identifies a tuple/row, prevents duplicates, entity integrity).
- 1.5 marks: Correct explanation of foreign key (references primary key in another table, links tables, referential integrity).
Question 14 · Structured Design / SQL / Trace
8.3 marks
An online shopping platform applies loyalty discounts based on the following rules:
- Premium Members (P) receive a base 10% discount.
- Orders over $150 (O) receive a base 10% discount.
- If a customer is a Premium Member AND their order is over $150, they receive a 20% discount instead of 10%.
- Customers with a Special Coupon (C) receive an extra 5% discount added to their base discount (e.g. 10% base discount becomes 15%, and 20% becomes 25%). If no other criteria are met, the coupon gives a 5% discount.
- Non-premium members with orders of $150 or less and no coupon receive 0% discount.

(a) Complete a decision table representing this policy. Identify the 3 conditions (C1: Premium Member, C2: Order > $150, C3: Special Coupon), show all 8 possible rule combinations, and select the correct action (0%, 5%, 10%, 15%, 20%, 25% discount) for each. [6 marks]

(b) State one reason why a developer would choose to use a decision table rather than pseudocode to specify complex business rules. [2.3 marks]
Show answer & marking scheme

Worked solution

Part (a):
Let C1 = Premium Member, C2 = Order > $150, C3 = Special Coupon.
There are \( 2^3 = 8 \) possible condition combinations:
- **Rule 1 (Y, Y, Y)**: Both C1 and C2 are true, making the base discount 20%. Coupon (C3) adds 5%. Action = **25%**.
- **Rule 2 (Y, Y, N)**: Both C1 and C2 are true, base discount is 20%. No coupon. Action = **20%**.
- **Rule 3 (Y, N, Y)**: Premium member (10% base) + Coupon (+5%). Action = **15%**.
- **Rule 4 (Y, N, N)**: Premium member (10% base) only. Action = **10%**.
- **Rule 5 (N, Y, Y)**: Order > $150 (10% base) + Coupon (+5%). Action = **15%**.
- **Rule 6 (N, Y, N)**: Order > $150 (10% base) only. Action = **10%**.
- **Rule 7 (N, N, Y)**: Coupon only (+5% base of 0%). Action = **5%**.
- **Rule 8 (N, N, N)**: No discounts applicable. Action = **0%**.

Part (b):
Decision tables prevent logical errors by forcing the developer to address all possible logic outcomes. They are also easier to read and maintain compared to heavily nested `IF-THEN-ELSE` statement structures in pseudocode.

Marking scheme

Part (a) [6 marks]:
- 1 mark: Identifying conditions C1, C2, C3 and listing 8 distinct combinations (binary combinations).
- 1 mark: Correctly mapping Rules 1 & 2 (25% and 20%).
- 1 mark: Correctly mapping Rules 3 & 4 (15% and 10%).
- 1 mark: Correctly mapping Rules 5 & 6 (15% and 10%).
- 1 mark: Correctly mapping Rules 7 & 8 (5% and 0%).
- 1 mark: Constructing actions block with clear selection marks (X).

Part (b) [2.3 marks]:
- 2.3 marks: Stating a valid advantage, e.g., ensures logical completeness, avoids nested code spaghetti, makes business rules clear to non-programmers, simplifies testing strategy.
Question 15 · Structured Design / SQL / Trace
8.3 marks
A structure chart represents the modular design of a library system. The module `ManageReturns` calls two sub-modules: `CheckOverdue` and `CalculateFine`.
- `ManageReturns` passes `BookID` and `MemberID` to `CheckOverdue`.
- `CheckOverdue` returns a control flag `IsOverdue` and an integer `DaysLate`.
- If `IsOverdue` is true, `ManageReturns` passes `DaysLate` to `CalculateFine`.
- `CalculateFine` returns the decimal value `FineAmount` to `ManageReturns`.

(a) Identify the names of:
(i) the modules in this structure chart. [1.5 marks]
(ii) the data couples passed between modules and their directions. [2.5 marks]
(iii) the control couple(s) and their directions. [1.3 marks]

(b) Explain:
(i) What is meant by 'high cohesion' in modular program design. [1.5 marks]
(ii) Why 'loose coupling' is desirable. [1.5 marks]
Show answer & marking scheme

Worked solution

Part (a):
- (i) **Modules**: The rectangular blocks in the hierarchy. Here, they are `ManageReturns` (the coordinator), `CheckOverdue`, and `CalculateFine` (the subordinates).
- (ii) **Data Couples**: Data passed. Direction must be explicitly specified:
- `BookID` and `MemberID`: passed from `ManageReturns` down to `CheckOverdue`.
- `DaysLate`: passed from `CheckOverdue` up to `ManageReturns`, and then from `ManageReturns` down to `CalculateFine`.
- `FineAmount`: passed from `CalculateFine` up to `ManageReturns`.
- (iii) **Control Couples**: Flags that control execution flow. Here, `IsOverdue` is passed from `CheckOverdue` up to `ManageReturns`.

Part (b):
- (i) **High Cohesion**: Cohesion measures how strongly-focused the tasks performed by a single module are. A highly cohesive module performs one distinct task (e.g., calculating a fine) which makes it easier to write, understand, and debug.
- (ii) **Loose Coupling**: Coupling measures the strength of connections between different modules. Loose coupling is desirable because it makes modules independent. This increases reusability, reduces dependencies, and limits the propagation of errors when code is changed.

Marking scheme

Part (a) [5.3 marks]:
- 1.5 marks: Identifying all three modules (0.5 marks each).
- 2.5 marks: Identifying all data couples with correct directions (0.5 marks per direction-couple combination).
- 1.3 marks: Identifying `IsOverdue` as the control flag with the direction from `CheckOverdue` to `ManageReturns`.

Part (b) [3 marks]:
- 1.5 marks: Explanation of high cohesion (single clear focus/task, self-contained purpose).
- 1.5 marks: Explanation of why loose coupling is desirable (module independence, reduces side effects, increases reusability).
Question 16 · Structured Design / SQL / Trace
8.3 marks
The following pseudocode algorithm implements a search on an array of integers:

```
DECLARE List : ARRAY[1..8] OF INTEGER
DECLARE Left, Right, SearchVal, Mid, Found : INTEGER
List[1] <-- 3
List[2] <-- 8
List[3] <-- 12
List[4] <-- 19
List[5] <-- 21
List[6] <-- 27
List[7] <-- 35
List[8] <-- 43

SearchVal <-- 27
Left <-- 1
Right <-- 8
Found <-- -1

WHILE Left <= Right AND Found = -1
Mid <-- (Left + Right) DIV 2
IF List[Mid] = SearchVal THEN
Found <-- Mid
ELSE
IF List[Mid] < SearchVal THEN
Left <-- Mid + 1
ELSE
Right <-- Mid - 1
ENDIF
ENDIF
ENDWHILE
```

(a) Complete the trace table to show the values of the variables as the algorithm executes. Draw a line in a cell to indicate no change in value. [5.3 marks]

(b) State the name of this search algorithm and explain one essential requirement for the array `List` for this algorithm to work correctly. [3 marks]
Show answer & marking scheme

Worked solution

Part (a):
Let's trace the loop step-by-step:
- **Initial values**: `SearchVal` = 27, `Left` = 1, `Right` = 8, `Found` = -1.
- **Iteration 1**:
- Loop condition `1 <= 8 AND -1 = -1` is True.
- `Mid = (1 + 8) DIV 2 = 4`.
- `List[Mid]` = `List[4]` = 19.
- Check `19 = 27` (False).
- Check `19 < 27` (True). `Left` becomes `Mid + 1` = `5`.
- **Iteration 2**:
- Loop condition `5 <= 8 AND -1 = -1` is True.
- `Mid = (5 + 8) DIV 2 = 6`.
- `List[Mid]` = `List[6]` = 27.
- Check `27 = 27` (True). `Found` becomes `6`.
- **Exit condition**:
- Loop condition `5 <= 8 AND 6 = -1` is False. The loop terminates.

Part (b):
- **Algorithm name**: Binary Search.
- **Requirement**: The data array must be sorted. If the elements are unsorted, dividing the search space in half by comparing with the midpoint is logically invalid and will fail to find existing values.

Marking scheme

Part (a) [5.3 marks]:
- 1.3 marks: Correct initial values row (`Left` = 1, `Right` = 8, `Found` = -1, other variables blank).
- 2 marks: Correct first iteration row (`Mid` = 4, `List[Mid]` = 19, `Left` = 5, other variables unchanged).
- 2 marks: Correct second iteration row (`Mid` = 6, `List[Mid]` = 27, `Found` = 6).

Part (b) [3 marks]:
- 1.5 marks: Identifying 'Binary Search'.
- 1.5 marks: Stating and explaining the requirement for the array to be sorted (ascending or descending order).

Paper 23 (Programming Skills)

Answer all questions. Refer to the insert for pseudocode functions.
8 Question · 75 marks
Question 1 · Logic evaluation & tracing
5 marks
Consider the following pseudocode algorithm:

```pseudocode
DECLARE x, y, z : INTEGER
x <-- 12
y <-- 5
z <-- 0
WHILE x > 0 DO
IF x MOD 2 <> 0 THEN
z <-- z + y
ENDIF
x <-- x DIV 2
y <-- y * 2
ENDWHILE
```

Complete the tracing of this algorithm. State:
1. The final values of x, y, and z when the loop terminates.
2. The number of times the WHILE loop condition evaluates to TRUE.
Show answer & marking scheme

Worked solution

Let's trace the execution of the algorithm step-by-step:
- Initial state: x = 12, y = 5, z = 0
- Iteration 1: The condition (x > 0) is 12 > 0, which is TRUE. x MOD 2 <> 0 (12 MOD 2 <> 0) is FALSE. x becomes 12 DIV 2 = 6. y becomes 5 * 2 = 10.
- Iteration 2: The condition (x > 0) is 6 > 0, which is TRUE. x MOD 2 <> 0 (6 MOD 2 <> 0) is FALSE. x becomes 6 DIV 2 = 3. y becomes 10 * 2 = 20.
- Iteration 3: The condition (x > 0) is 3 > 0, which is TRUE. x MOD 2 <> 0 (3 MOD 2 <> 0) is TRUE. z becomes z + y = 0 + 20 = 20. x becomes 3 DIV 2 = 1. y becomes 20 * 2 = 40.
- Iteration 4: The condition (x > 0) is 1 > 0, which is TRUE. x MOD 2 <> 0 (1 MOD 2 <> 0) is TRUE. z becomes z + y = 20 + 40 = 60. x becomes 1 DIV 2 = 0. y becomes 40 * 2 = 80.
- Iteration 5: The condition (x > 0) is 0 > 0, which is FALSE. The loop terminates.

Final values: x = 0, y = 80, z = 60. The loop condition evaluated to TRUE 4 times.

Marking scheme

1 mark: Correct final value of x (0)
1 mark: Correct final value of y (80)
1 mark: Correct final value of z (60)
1 mark: Evidence of tracing intermediate state of z (reaching 20 during loop)
1 mark: Correct number of loop iterations (4)
Question 2 · Logic evaluation & tracing
5 marks
A programmer designs the following pseudocode function to evaluate permissions:

```pseudocode
FUNCTION CheckAccess(Age : INTEGER, HasParent : BOOLEAN, VIP : BOOLEAN) RETURNS BOOLEAN
DECLARE Allowed : BOOLEAN
Allowed <-- (Age >= 18 OR (Age >= 12 AND HasParent)) AND NOT (VIP = FALSE AND Age < 15)
RETURN Allowed
ENDFUNCTION
```

Evaluate the function call outputs for the following five test cases. State whether each call returns TRUE or FALSE:

1. CheckAccess(15, TRUE, FALSE)
2. CheckAccess(12, TRUE, FALSE)
3. CheckAccess(17, FALSE, TRUE)
4. CheckAccess(18, FALSE, FALSE)
5. CheckAccess(14, TRUE, TRUE)
Show answer & marking scheme

Worked solution

Let's evaluate each logical expression step-by-step:

1. CheckAccess(15, TRUE, FALSE):
- Left side: (15 >= 18 OR (15 >= 12 AND TRUE)) -> (FALSE OR (TRUE AND TRUE)) -> TRUE.
- Right side: NOT (FALSE = FALSE AND 15 < 15) -> NOT (TRUE AND FALSE) -> NOT (FALSE) -> TRUE.
- Allowed <-- TRUE AND TRUE = TRUE.

2. CheckAccess(12, TRUE, FALSE):
- Left side: (12 >= 18 OR (12 >= 12 AND TRUE)) -> (FALSE OR (TRUE AND TRUE)) -> TRUE.
- Right side: NOT (FALSE = FALSE AND 12 < 15) -> NOT (TRUE AND TRUE) -> NOT (TRUE) -> FALSE.
- Allowed <-- TRUE AND FALSE = FALSE.

3. CheckAccess(17, FALSE, TRUE):
- Left side: (17 >= 18 OR (17 >= 12 AND FALSE)) -> (FALSE OR FALSE) -> FALSE.
- Since Left side is FALSE, the entire expression evaluation with AND results in FALSE.
- Allowed <-- FALSE.

4. CheckAccess(18, FALSE, FALSE):
- Left side: (18 >= 18 OR ...) -> TRUE OR ... -> TRUE.
- Right side: NOT (FALSE = FALSE AND 18 < 15) -> NOT (TRUE AND FALSE) -> NOT (FALSE) -> TRUE.
- Allowed <-- TRUE AND TRUE = TRUE.

5. CheckAccess(14, TRUE, TRUE):
- Left side: (14 >= 18 OR (14 >= 12 AND TRUE)) -> (FALSE OR TRUE) -> TRUE.
- Right side: NOT (TRUE = FALSE AND 14 < 15) -> NOT (FALSE AND TRUE) -> NOT (FALSE) -> TRUE.
- Allowed <-- TRUE AND TRUE = TRUE.

Marking scheme

1 mark for each correct logical evaluation:
- Case 1: TRUE
- Case 2: FALSE
- Case 3: FALSE
- Case 4: TRUE
- Case 5: TRUE
Question 3 · Logic evaluation & tracing
5 marks
The following pseudocode algorithm performs a sequence of operations on a 1-dimensional array, Arr:

```pseudocode
DECLARE Arr : ARRAY[1..6] OF INTEGER
DECLARE i, temp : INTEGER
Arr[1] <-- 8
Arr[2] <-- 3
Arr[3] <-- 5
Arr[4] <-- 8
Arr[5] <-- 2
Arr[6] <-- 7

FOR i <-- 1 TO 5
IF Arr[i] > Arr[i+1] THEN
temp <-- Arr[i]
Arr[i] <-- Arr[i+1]
Arr[i+1] <-- temp
ENDIF
NEXT i
```

Trace the execution of this algorithm and determine:
1. The final values contained in the array Arr from index 1 to 6.
2. The total number of times a swap (the block inside the IF statement) is executed.
Show answer & marking scheme

Worked solution

Let's trace each iteration of the FOR loop step-by-step:
- Initial State: Arr = [8, 3, 5, 8, 2, 7]

- i = 1: Is Arr[1] > Arr[2]? (8 > 3 is TRUE). Swap Arr[1] and Arr[2].
Arr becomes: [3, 8, 5, 8, 2, 7]. Swap count = 1.

- i = 2: Is Arr[2] > Arr[3]? (8 > 5 is TRUE). Swap Arr[2] and Arr[3].
Arr becomes: [3, 5, 8, 8, 2, 7]. Swap count = 2.

- i = 3: Is Arr[3] > Arr[4]? (8 > 8 is FALSE). No swap occurs.
Arr remains: [3, 5, 8, 8, 2, 7]. Swap count = 2.

- i = 4: Is Arr[4] > Arr[5]? (8 > 2 is TRUE). Swap Arr[4] and Arr[5].
Arr becomes: [3, 5, 8, 2, 8, 7]. Swap count = 3.

- i = 5: Is Arr[5] > Arr[6]? (8 > 7 is TRUE). Swap Arr[5] and Arr[6].
Arr becomes: [3, 5, 8, 2, 7, 8]. Swap count = 4.

Final State: Arr = [3, 5, 8, 2, 7, 8] with exactly 4 swaps performed.

Marking scheme

3 marks for the final elements of Arr:
- 3 marks: all 6 elements correct: [3, 5, 8, 2, 7, 8]
- 2 marks: 4 or 5 elements correct
- 1 mark: 2 or 3 elements correct
2 marks for correct count of swaps:
- 2 marks: exactly 4 swaps
- 1 mark: incorrect final count but evidence of tracing intermediate swaps
Question 4 · Logic evaluation & tracing
5 marks
The following pseudocode function processes a string character by character:

```pseudocode
FUNCTION ProcessString(InStr : STRING) RETURNS STRING
DECLARE OutStr : STRING
DECLARE i : INTEGER
DECLARE Ch : CHAR
OutStr <-- \"\"
FOR i <-- 1 TO LENGTH(InStr)
Ch <-- MID(InStr, i, 1)
IF Ch >= 'A' AND Ch <= 'Z' THEN
OutStr <-- OutStr & LCASE(Ch)
ELSEIF Ch >= 'a' AND Ch <= 'z' THEN
OutStr <-- UCASE(Ch) & OutStr
ELSE
OutStr <-- OutStr & \"*\"
ENDIF
NEXT i
RETURN OutStr
ENDFUNCTION
```

Notes on built-in functions:
- `MID(InStr, i, 1)` returns the character at position `i` (1-based index).
- `LCASE` / `UCASE` convert characters to lowercase/uppercase.
- `&` is the string concatenation operator.

Dry run the function with the input string `InStr = "mD8e"`. Show:
1. The value of `OutStr` at the end of each of the 4 loop iterations.
2. The final returned string.
Show answer & marking scheme

Worked solution

Let's trace the loop step-by-step with InStr = \"mD8e\" (Length = 4):
- Initial state: OutStr = \"\"
- Iteration 1 (i = 1): Ch = 'm'. Since 'm' is lowercase, the ELSEIF is met. OutStr becomes UCASE('m') & OutStr -> 'M' & \"\" = \"M\".
- Iteration 2 (i = 2): Ch = 'D'. Since 'D' is uppercase, the IF condition is met. OutStr becomes OutStr & LCASE('D') -> \"M\" & 'd' = \"Md\".
- Iteration 3 (i = 3): Ch = '8'. It is neither upper nor lowercase, so the ELSE block is met. OutStr becomes OutStr & \"*\" -> \"Md\" & \"*\" = \"Md*\".
- Iteration 4 (i = 4): Ch = 'e'. It is lowercase, so the ELSEIF condition is met. OutStr becomes UCASE('e') & OutStr -> 'E' & \"Md*\" = \"EMd*\".

After the loop finishes, the function returns OutStr, which is \"EMd*\".

Marking scheme

1 mark for each correct value of OutStr at the end of each iteration (total 4 marks):
- Iteration 1: \"M\"
- Iteration 2: \"Md\"
- Iteration 3: \"Md*\"
- Iteration 4: \"EMd*\"
1 mark for the correct final return value: \"EMd*\"
Question 5 · Pseudocode implementation
13.75 marks
A school library stores book reservation requests in a global 2D array, `ReservationList`, of type `STRING` with dimensions `[1:100, 1:3]`. The columns are:
- `[i, 1]`: Student ID
- `[i, 2]`: Book ID
- `[i, 3]`: Reservation Status (can be "PENDING", "APPROVED", or "REJECTED")

Another global 2D array, `BookStock`, of type `STRING` with dimensions `[1:50, 1:2]` stores the actual book inventory. The columns are:
- `[j, 1]`: Book ID
- `[j, 2]`: Current Available Quantity (stored as a string, e.g., "3")

Write a pseudocode function `ProcessReservations(BYREF ReservationList : ARRAY, BYREF BookStock : ARRAY) RETURNS INTEGER` that updates pending reservations:
1. It must iterate through all 100 entries in `ReservationList`.
2. For each reservation with a status of "PENDING", it must locate the corresponding `Book ID` in the `BookStock` array.
3. If the book is found in `BookStock` and its available quantity is greater than 0, decrease the quantity by 1, update the reservation status to "APPROVED", and count it.
4. If the book is found but the quantity is 0, update the reservation status to "REJECTED".
5. Finally, the function must return the total number of approved reservations during this process.

You should assume that the built-in functions `STR_TO_NUM(s : STRING) RETURNS INTEGER` and `NUM_TO_STR(n : INTEGER) RETURNS STRING` are available.
Show answer & marking scheme

Worked solution

The function initializes an integer counter `ApprovedCount` to 0. It iterates through each row of the `ReservationList` array from 1 to 100. If the reservation status is found to be "PENDING", it grabs the `Book ID` from the second column. It then performs a sequential search on `BookStock` to find a matching `Book ID`. Once located, it parses the quantity string using `STR_TO_NUM`. If this value is greater than 0, it is decremented by 1, saved back into `BookStock` as a string using `NUM_TO_STR`, and the reservation status is changed to "APPROVED" while incrementing the counter. If no stock was available, the status becomes "REJECTED". Finally, `ApprovedCount` is returned.

Marking scheme

- 1.5 Marks: Correct FUNCTION header with parameter definitions and returns standard INTEGER type.
- 2 Marks: Loop correctly setup to iterate through all 100 elements.
- 2 Marks: Check for "PENDING" status before trying to process elements.
- 2 Marks: Inner linear search loop on `BookStock` (1 to 50) with termination on found.
- 2 Marks: Correct type conversions using `STR_TO_NUM` and `NUM_TO_STR`.
- 2.25 Marks: Correct decrement of stock value, update to "APPROVED" status, and accumulation of count.
- 1 Mark: Correctly updates status to "REJECTED" when stock is zero.
- 1 Mark: Correct return of overall approved count and ENDFUNCTION structure.
Question 6 · Pseudocode implementation
13.75 marks
A text file `transactions.txt` contains transaction records on each line in the format: `CustomerID,Amount,Currency` (e.g., "C104,120.50,USD").

Write a pseudocode procedure `ValidateTransactions(FileName : STRING)` that processes this file. The procedure must perform the following:
1. Open `transactions.txt` for reading.
2. Open `valid.txt` and `errors.txt` for writing.
3. Read each record from `transactions.txt` line by line until the end of the file is reached.
4. Validate each transaction line:
- **Customer ID**: Must be exactly 4 characters long, must start with 'C', and the remaining 3 characters must be numeric digits ('0'-'9').
- **Currency**: Must be exactly "USD", "EUR", or "GBP".
- **Amount**: Must be a positive real number (> 0).
5. If a transaction is valid, write the original line exactly as it is to `valid.txt`.
6. If a transaction is invalid, write the original line to `errors.txt` appended with a comma and its corresponding line number in the source file (e.g., "C104,120.50,USD,4" for an error on line 4).
7. Close all opened files.

Assume the helper function `GetField(RecordStr : STRING, FieldNum : INTEGER) RETURNS STRING` exists to extract a field index (1, 2, or 3) from the comma-separated string, and `STR_TO_REAL(s : STRING) RETURNS REAL` converts a string to a decimal value.
Show answer & marking scheme

Worked solution

The procedure begins by opening the three files (the input file and the two output files). Inside a `WHILE` loop checking `EOF(FileName)`, it parses each field using the `GetField` function. The customer ID is validated by first checking its length, checking the first character using `SUBSTRING`, and iterating over characters 2 to 4 to check if they are in the range "0" to "9". The currency is checked against the three allowed strings. The amount is validated after converting it with `STR_TO_REAL`. If any validation fails, the `Valid` flag is set to `FALSE`. Finally, the transaction is written to the appropriate file, and the files are closed before exiting.

Marking scheme

- 1.5 Marks: Procedure header, declaration of files and variables.
- 2 Marks: Opening all three files with correct read/write permissions.
- 2 Marks: Loop control using `NOT EOF()` and maintaining accurate incrementing line number.
- 2 Marks: Correct string parsing using `GetField()` helper to isolate Customer ID, Currency, and Amount.
- 2 Marks: Validation of Customer ID length, prefix ('C'), and loop iteration validating remaining characters as numeric digits.
- 2 Marks: Validation logic for currency values and numeric verification of the transaction amount.
- 2.25 Marks: Proper output to target files with error logging of the original line and current index, along with closing all opened file buffers.
Question 7 · Pseudocode implementation
13.75 marks
Write a pseudocode function `CompressString(InputStr : STRING) RETURNS STRING` that performs basic run-length encoding.

The function takes a string of uppercase alphabetic characters and returns a compressed string where consecutive duplicate characters are replaced with the count of duplicates followed by the character itself.

For example:
- `"AAAABBC"` compresses to `"4A2B1C"`
- `"X"` compresses to `"1X"`
- An empty input string `""` returns an empty string `""`.

You should assume that the built-in functions `LENGTH(s : STRING) RETURNS INTEGER`, `SUBSTRING(s : STRING, start : INTEGER, length : INTEGER) RETURNS STRING`, and `NUM_TO_STR(n : INTEGER) RETURNS STRING` are available.
Show answer & marking scheme

Worked solution

The function first determines the length of `InputStr`. If it is 0, it returns `""`. It then initializes `OutputStr` to empty, sets `CurrentChar` to the first character of the string, and sets `Count` to 1. It loops from index 2 to the end of the string. If the current character is equal to `CurrentChar`, `Count` is incremented. Otherwise, the formatted count and previous character are concatenated to `OutputStr`, `CurrentChar` is updated to the new character, and `Count` is reset to 1. After the loop ends, the remaining block count and character must be appended to the output string before returning it.

Marking scheme

- 1 Mark: Correct FUNCTION header and RETURNS declaration.
- 1.5 Marks: Handling empty input edge-case correctly.
- 2 Marks: Initialization of output string, tracking character, and starting index count.
- 3 Marks: A loop from index 2 to string length.
- 2 Marks: Comparison check using `SUBSTRING` and incrementing the count for consecutive matching characters.
- 2 Marks: Handling character transition: appending `NUM_TO_STR(Count) & CurrentChar` to `OutputStr` and resetting variables.
- 2.25 Marks: Appending the final remaining run of characters after loop termination, and correct use of standard string concatenation.
Question 8 · Pseudocode implementation
13.75 marks
A logistics system uses a custom Record type `Package` to hold shipment details:
```
TYPE Package
DECLARE PackageID : STRING
DECLARE Weight : REAL
DECLARE Destination : STRING
DECLARE Delivered : BOOLEAN
ENDTYPE
```

Write a pseudocode procedure `GenerateManifest(Manifest : ARRAY[1:200] OF Package, TargetDest : STRING)` that parses an array of package records and performs the following tasks:
1. Search through the entire 200 elements of the array.
2. For every package that matches the `TargetDest` and is **not** delivered (`Delivered = FALSE`):
- Output the `PackageID` and `Weight` fields.
- Accumulate the weight of these matching packages to compute the total weight of outstanding deliveries for that destination.
- Keep track of the ID of the heaviest matching package.
3. After searching through all elements, if matches were found, output:
- The total accumulated weight of undelivered packages.
- The `PackageID` of the heaviest undelivered package.
4. If no matching packages were found, output "No undelivered packages for destination: [TargetDest]".
Show answer & marking scheme

Worked solution

The procedure initializes standard variables: `TotalWeight` to 0.0, `MaxWeight` to a negative value to guarantee any valid package will exceed it, `FoundMatch` to `FALSE`, and `HeaviestID` to an empty string. A `FOR` loop iterates through the indexes 1 to 200 of the `Manifest` array. Inside, an conditional statement checks if `Manifest[Index].Destination` matches `TargetDest` and `Manifest[Index].Delivered` is `FALSE`. If both are true, the package information is printed, the weight is added to the `TotalWeight`, and a selection construct checks if this weight is the largest seen so far. Finally, the procedure outputs the totals or prints an error message if `FoundMatch` remains `FALSE`.

Marking scheme

- 1.5 Marks: Correct PROCEDURE header with parameters (array of Package, string).
- 1 Mark: Variable declarations and initializations of logic variables.
- 2 Marks: Loop bounds matching precisely (1 to 200).
- 3 Marks: Valid syntax using record attribute dot-notation (e.g. `Manifest[Index].Destination`) and correct logical AND conditions.
- 2 Marks: Correctly outputs matching Package information and accumulates `TotalWeight` accurately.
- 2.25 Marks: Implementation of robust selection logic tracking `MaxWeight` and retaining the corresponding `HeaviestID` value.
- 2 Marks: Condition logic checking `FoundMatch` to decide whether to output totals or a designated custom message.

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