An original Thinka practice paper modelled on the structure and difficulty of the Jun 2024 (V2) 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.
Describe the operation of the following logic gates: (i) A 2-input XOR (Exclusive OR) gate. [2 marks] (ii) A 2-input NAND (Not AND) gate. [2 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(i) A 2-input XOR gate outputs 1 when the two inputs have different values (one high and one low), and outputs 0 when the inputs are the same (both low or both high). (ii) A 2-input NAND gate produces an output of 0 only when both inputs are 1. If any input is 0, the output is 1, which represents the inverse of a standard AND gate.
PastPaper.markingScheme
Part (i) XOR gate [Max 2 marks]: 1 mark for stating output is 1 when inputs are different. 1 mark for stating output is 0 when inputs are the same. Part (ii) NAND gate [Max 2 marks]: 1 mark for stating output is 0 only when both inputs are 1. 1 mark for stating output is 1 if at least one input is 0 (or output is inverse of AND gate).
PastPaper.question 2 · Structured
4 PastPaper.marks
Complete the sentences about different types of utility software by filling in the missing words.
Disk defragmentation is a utility that reorganizes fragmented files on a magnetic hard drive. It attempts to store all the sectors of a single file in (a) __________ storage locations. This reduces the movement of the read-write head, thereby improving system (b) __________.
An (c) __________ backup is a type of backup utility that only copies files that have changed or been created since the last backup was performed.
A (d) __________ utility is used to reduce the size of a file, making it quicker to transmit over a network.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) contiguous: Defragmentation rearranges sectors so that files are stored in contiguous (continuous/consecutive) blocks, minimizing disk head movement. (b) performance: Reduced physical movement of the read-write head results in faster file access, increasing overall system performance or speed. (c) incremental: Unlike a full backup, an incremental backup only saves files that have been modified or newly created since the last backup of any type. (d) compression: Compression algorithms reduce the file size by removing redundancy (lossless) or unnecessary data (lossy), which decreases transmission time.
PastPaper.markingScheme
1 mark for each correct term up to 4 marks: - (a) contiguous (Accept: consecutive / continuous) - (b) performance (Accept: speed / read-write speed / response time / throughput / efficiency) - (c) incremental - (d) compression (Accept: data compression / file compression)
PastPaper.question 3 · short-answer
3 PastPaper.marks
A computer system uses a buffer when transferring data from primary memory to an external secondary storage device. Describe the role of the buffer in this data transfer.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. The buffer acts as a temporary storage area to bridge the speed gap between primary memory and the slower secondary storage device. 2. Data is transferred from RAM to the buffer at high speed. This allows the CPU to continue with other operations instead of idling during the slow write process. 3. The secondary storage device reads data from the buffer at its native, slower transfer speed. When the buffer is empty, a hardware interrupt is generated to request more data from RAM.
PastPaper.markingScheme
Award 1 mark per point up to a maximum of 3: - Buffer acts as a temporary storage/holding area (to compensate for speed differences). - CPU sends data to the buffer at high speed, allowing the CPU to continue with other processing tasks / prevents CPU idling. - Slower secondary storage device reads/writes data from the buffer at its own speed. - An interrupt is sent to the CPU when the buffer is empty to request more data.
PastPaper.question 4 · short-answer
3 PastPaper.marks
Explain the differences between Programmable ROM (PROM), Erasable Programmable ROM (EPROM), and Electrically Erasable Programmable ROM (EEPROM) with respect to how they are programmed and erased.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. PROM (Programmable ROM) is purchased blank and can only be written to/programmed once. Once programmed, it cannot be erased or modified. 2. EPROM (Erasable Programmable ROM) can be erased by exposing the chip to ultraviolet (UV) light through a quartz window, after which it can be reprogrammed. 3. EEPROM (Electrically Erasable Programmable ROM) can be erased and reprogrammed using electrical signals without being removed from the circuit board.
PastPaper.markingScheme
Award 1 mark for each explanation (max 3): - PROM: Programmed once only / cannot be erased or rewritten. - EPROM: Erased using ultraviolet (UV) light (before being reprogrammed). - EEPROM: Erased/reprogrammed electrically (in-circuit).
PastPaper.question 5 · descriptive
2.5 PastPaper.marks
Describe how a vector graphic is represented in a computer system, and explain why its file size does not increase when the image is scaled up.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Vector graphics are stored as a set of drawing instructions and geometric objects (such as lines, curves, and shapes). 2. Each object is defined mathematically by properties such as start/end coordinates, radius, width, line thickness, and fill colour. 3. Scaling a vector graphic does not require adding more pixels; instead, the computer recalculates the mathematical equations to draw the shapes at the new scale. Because the number of shapes and their instruction data remains constant, the file size does not increase.
PastPaper.markingScheme
Award up to 2.5 marks: - 1 mark: Stating that vector graphics are stored as drawing commands/instructions or geometric shapes defined by mathematical formulas. - 1 mark: Stating that shapes have properties/attributes (e.g., coordinates, thickness, fill colour). - 0.5 marks: Explaining that scaling only recalculates these formulas, so no additional pixels/data are stored, keeping the file size constant.
PastPaper.question 6 · descriptive
2.5 PastPaper.marks
An analogue audio signal is converted into digital format using sound sampling. Describe how the sampling rate and sampling resolution (bit depth) affect the fidelity (accuracy) of the recorded sound and its resulting file size.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Sampling rate is the number of samples taken per second. A higher rate captures more frequent sound measurements, improving fidelity (capturing higher frequencies) but increasing file size as more data points must be stored. 2. Sampling resolution (bit depth) is the number of bits allocated per sample. A higher resolution reduces quantization error, allowing more precise representation of amplitude (improving fidelity) but increasing file size since each sample requires more bits. 3. Both factors directly scale the overall file size: \(File\ Size = Sampling\ Rate \times Sampling\ Resolution \times Duration\).
PastPaper.markingScheme
Award up to 2.5 marks: - 1 mark: Explaining sampling rate (more frequent samples/higher fidelity vs. more data points/larger file size). - 1 mark: Explaining sampling resolution (more bits per sample/reduced quantization error vs. larger file size). - 0.5 marks: Stating or showing that file size is directly proportional to both factors (e.g., through the relationship/formula).
PastPaper.question 7 · descriptive
3 PastPaper.marks
A network administrator configures a packet-filtering firewall to protect the company's internal network. Describe how a packet-filtering firewall controls the flow of traffic into and out of the network.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A packet-filtering firewall functions by checking data packets against a set of security criteria. Specifically, it: 1. Inspects the header of each incoming and outgoing packet to extract key transmission details. 2. Compares these packet attributes (such as the source IP address, destination IP address, port number, or protocol) against a pre-determined database of security rules (Access Control Lists). 3. Decides to either allow the packet to pass through to its destination or block/drop the packet if it violates the rules.
PastPaper.markingScheme
Award 1 mark for each of the following points, up to a maximum of 3 marks: - Explains that the firewall inspects/analyzes the packet headers of incoming and/or outgoing data. - States that it compares packet details (e.g., source/destination IP address, port number, protocol) against a pre-defined set of security rules/filters. - Explains that it allows or blocks/drops the packets depending on whether they meet the specified rules.
PastPaper.question 8 · descriptive
3 PastPaper.marks
State the purpose of Transport Layer Security (TLS) and describe how it protects data during transmission between a client computer and a web server.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Transport Layer Security (TLS) is a cryptographic protocol designed to secure internet communications. 1. Purpose: To ensure confidentiality, integrity, and authenticity of data sent over the network. 2. How it works: - A handshake is initiated where the client verifies the identity of the server using its digital certificate. - The client and server agree on a symmetric session key. - All subsequent data sent between the client and server is encrypted using this session key, preventing eavesdropping and tampering.
PastPaper.markingScheme
Award 1 mark for each of the following points, up to a maximum of 3 marks: - Purpose: To provide secure/private/encrypted communication (or protect confidentiality/integrity of data) over a network. - Authentication: The client authenticates the server's identity using its digital certificate. - Encryption: A symmetric session key is negotiated during the handshake, and all subsequent data transmitted is encrypted using this key.
PastPaper.question 9 · short-answer
4 PastPaper.marks
An organization is setting up a shared database system and decides to implement a client-server model instead of a peer-to-peer model. Describe four characteristics of a client-server model that make it suitable for a centralized database system.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
In a client-server architecture, responsibilities are partitioned between the service provider (server) and service requesters (clients). Characteristics suitable for a centralized database include: Centralised security (ensuring data access rules are enforced universally), Centralised backup (enabling routine automated backups of the entire database in one place), Centralised data integrity (avoiding conflicting local copies of database records), and Resource sharing (allowing many clients to query and update the same data store concurrently).
PastPaper.markingScheme
Award 1 mark for each valid characteristic described up to a maximum of 4 marks: - Centralised security / Access control: User accounts, access rights, and permissions are managed centrally by the server. - Centralised backup: Data can be backed up in a single location rather than needing individual backups on every machine. - Centralised data storage / Consistency: Ensures all users access the same, most up-to-date version of the database files. - Performance/Division of labour: Server processes intensive database queries (back-end) while client manages user interface (front-end). - Scalability: It is easier to add new clients to the network without degrading the central database structure. (Do not accept generic benefits of networks like 'can share printers' unless directly linked to database operations.)
PastPaper.question 10 · Written Explanation
2 PastPaper.marks
Describe the purpose of a routing table and explain how a router uses it when a packet is received.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A routing table is a database stored in a router that lists the routes to particular network destinations. When a packet is received, the router reads the destination IP address in the packet header, matches it with the best route in the routing table, and forwards the packet to the corresponding output interface.
PastPaper.markingScheme
Award up to 2 marks: 1 mark for stating that the routing table stores network destination paths or next-hop information. 1 mark for explaining that the router compares the destination IP of the incoming packet with the table to find the appropriate outgoing route.
PastPaper.question 11 · Written Explanation
2 PastPaper.marks
Explain how a router uses the Time to Live (TTL) value in an IP packet header, and state why this action is necessary.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
As a packet passes through a router, the router decreases the TTL value by 1. If the TTL reaches 0, the packet is discarded and not forwarded. This prevents packets from traveling infinitely in routing loops and causing network congestion.
PastPaper.markingScheme
Award up to 2 marks: 1 mark for explaining that the router decrements the TTL value by 1 (and/or discards the packet if TTL reaches 0). 1 mark for stating that this prevents packets from circulating endlessly / looping indefinitely in the network.
PastPaper.question 12 · SQL Structural Scripting
2.66 PastPaper.marks
A database is used to manage a dental practice. A table named Appointment needs to be created to store appointment details. The table has the following fields: - AppointmentID: integer, primary key. - PatientID: integer, foreign key referencing the Patient table. - AppointmentDate: date. - FeeCharged: currency/decimal (up to 5 digits in total, with 2 decimal places). Write a SQL script to create the table Appointment with these specifications.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The SQL script to create the table requires: 1. CREATE TABLE statement with field names and correct data types. 2. Definition of the primary key. 3. Definition of the foreign key referencing the parent table. SQL statement: CREATE TABLE Appointment ( AppointmentID INT NOT NULL, PatientID INT, AppointmentDate DATE, FeeCharged DECIMAL(5,2), PRIMARY KEY (AppointmentID), FOREIGN KEY (PatientID) REFERENCES Patient(PatientID) );
PastPaper.markingScheme
1 mark for correct CREATE TABLE and fields with correct data types (AppointmentID INT, PatientID INT, AppointmentDate DATE, FeeCharged DECIMAL(5,2)). 1 mark for correct PRIMARY KEY definition. 0.66 marks for correct FOREIGN KEY definition referencing Patient(PatientID).
PastPaper.question 13 · SQL Structural Scripting
2.66 PastPaper.marks
A database contains two tables: Department (DeptID, DeptName, ManagerName) and Employee (EmpID, EmpName, Salary, DeptID). Write a SQL query to display the EmpName, Salary, and DeptName for all employees who have a salary greater than 45000, ordered by Salary in descending order.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The SQL script requires: 1. SELECT clause listing EmpName, Salary, and DeptName. 2. FROM clause with join syntax (either INNER JOIN or implicit join). 3. WHERE clause to filter salaries > 45000. 4. ORDER BY clause sorting by Salary DESC.
PastPaper.markingScheme
1 mark for SELECT and FROM clause with correct INNER JOIN on DeptID. 1 mark for WHERE clause filtering Salary > 45000. 0.66 marks for ORDER BY Salary DESC.
PastPaper.question 14 · SQL Structural Scripting
2.66 PastPaper.marks
In a library database, a table named Book has the fields: BookID, Title, Author, Genre, and RentalPrice. Write a SQL script to increase the RentalPrice by 10% for all books where the Genre is 'Sci-Fi'.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The SQL query updates rows in the Book table. The SET clause sets the new RentalPrice to 1.10 times the current value. The WHERE clause restricts this change to books of the 'Sci-Fi' genre. SQL: UPDATE Book SET RentalPrice = RentalPrice * 1.10 WHERE Genre = 'Sci-Fi';
PastPaper.markingScheme
1 mark for UPDATE Book and SET RentalPrice = RentalPrice * 1.1 or equivalent. 1.66 marks for correct WHERE Genre = 'Sci-Fi' constraint.
PastPaper.question 15 · trace_table
3.5 PastPaper.marks
An assembly language program is executed. The table below shows the instruction set used:
| Instruction | Description | |---|---| | `LDD ` | Load the contents of the given address into the Accumulator (ACC). | | `LDM #n` | Load the denary number `n` into the Accumulator (ACC). | | `STO ` | Store the contents of the Accumulator (ACC) into the given address. | | `ADD ` | Add the contents of the given address to the contents of the Accumulator (ACC). | | `DEC ` | Decrement the contents of the given register (ACC) by 1. | | `CMP #n` | Compare the contents of the Accumulator (ACC) with denary number `n`. | | `JPN ` | Jump to the given label if the comparison is NOT equal. | | `END` | Terminate the program. |
At the start of execution, the memory addresses contain the following denary values: - **Address 200**: 3 - **Address 201**: 4 - **Address 202**: 0 - **Address 203**: 0
The program assembly code is as follows: ```assembly LDD 200 STO 202 LDM #0 STO 203 LOOP: LDD 203 ADD 201 STO 203 LDD 202 DEC ACC STO 202 CMP #0 JPN LOOP END ``` Complete the trace table for the execution of this program. Do not write duplicate values in a column unless the value actually changes.
- **1.0 Mark**: Correct updates to Memory address [202] with values `3`, `2`, `1`, `0` in correct chronological sequence. - **1.0 Mark**: Correct updates to Memory address [203] with values `0`, `4`, `8`, `12` in correct chronological sequence. - **1.5 Marks**: Correct sequence of values in the Accumulator (ACC) column: `3`, `0`, `4`, `3`, `2`, `4`, `8`, `2`, `1`, `8`, `12`, `1`, `0` (allow minor omissions with a 0.5-mark deduction per incorrect sequence change, up to 1.5 marks max).
PastPaper.question 16 · trace_table
3.5 PastPaper.marks
An assembly language program is executed. The table below shows the instruction set used:
| Instruction | Description | |---|---| | `LDD ` | Load the contents of the given address into the Accumulator (ACC). | | `LDM #n` | Load the denary number `n` into the Accumulator (ACC). | | `LDX ` | Indexed addressing: Load the contents of \( \text{address} + \text{IX} \) into ACC. | | `STO ` | Store the contents of the Accumulator (ACC) into the given address. | | `ADD ` | Add the contents of the given address to the contents of the Accumulator (ACC). | | `INC `| Increment the contents of the given register (ACC or IX) by 1. | | `DEC `| Decrement the contents of the given register (ACC) by 1. | | `CMP #n` | Compare the contents of the Accumulator (ACC) with denary number `n`. | | `JPN ` | Jump to the given label if the comparison is NOT equal. | | `END` | Terminate the program. |
At the start of execution, the register and memory states are as follows: - **IX**: 0 - **Address 150**: 12 - **Address 151**: 7 - **Address 152**: 15 - **Address 160 (Sum)**: 0 - **Address 161 (Counter)**: 0
The program assembly code is as follows: ```assembly LDM #3 STO 161 LDM #0 STO 160 LOOP: LDX 150 ADD 160 STO 160 INC IX LDD 161 DEC ACC STO 161 CMP #0 JPN LOOP END ``` Complete the trace table for the execution of this program. Do not write duplicate values in a column unless the value actually changes.
- **1.0 Mark**: Correct updates to `IX` (`1`, `2`, `3`) and Memory address [161] (`3`, `2`, `1`, `0`) in sequence. - **1.0 Mark**: Correct updates to Memory address [160] (`0`, `12`, `19`, `34`) in sequence. - **1.5 Marks**: Correct tracking of ACC changes: `3`, `0`, `12`, `3`, `2`, `7`, `19`, `2`, `1`, `15`, `34`, `1`, `0` (allow 0.5-mark deduction per tracking error up to 1.5 marks max).
PastPaper.question 17 · text
4 PastPaper.marks
An operating system manages processes using process states and a Process Control Block (PCB). Explain the sequence of events that occurs, in terms of process states and the PCB, when a running process initiates an Input/Output (I/O) operation, such as reading data from a disk.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
When a running process requests I/O, it cannot continue executing on the CPU immediately because I/O devices are slow. First, the process transitions from the Running state to the Blocked state. Second, the CPU saves the current state of the process (including the program counter and register values) into its Process Control Block (PCB) to allow future resumption. Third, the operating system scheduler selects a new process from the Ready queue to run, restoring its state from its respective PCB. Finally, once the I/O operation completes, an interrupt is sent to the CPU, and the operating system changes the state of the waiting process from Blocked to Ready so it can compete for CPU time again.
PastPaper.markingScheme
Award 1 mark for each of the following up to a maximum of 4 marks: - State transition 1: Running process transitions to the Blocked state. - Save State: The process's current state (registers, program counter) is saved into its Process Control Block (PCB). - Scheduling: The operating system/scheduler loads and runs a process from the Ready state. - State transition 2: When I/O completes, the process transitions from the Blocked state to the Ready state.
PastPaper.question 18 · short_answer
2 PastPaper.marks
Perform the binary addition of the following two 8-bit signed two's complement integers:
\(01011100\)
\(00110110\)
State the 8-bit binary result and explain why an overflow error has occurred.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To add the two binary numbers:
\(01011100\) (equivalent to denary \(+92\)) + \(00110110\) (equivalent to denary \(+54\)) ----------- \(10010010\) (equivalent to signed denary \(-110\))
An overflow error has occurred because the sum of two positive numbers has resulted in a negative number (the sign bit, MSB, is 1). Alternatively, \(92 + 54 = 146\), which is outside the range of 8-bit signed two's complement integers (\(-128\) to \(+127\)).
PastPaper.markingScheme
1 mark: Correct 8-bit binary result of the addition: \(10010010\). 1 mark: Clear explanation of why overflow occurred (e.g., adding two positive numbers resulted in a negative value / MSB is 1, OR the denary sum 146 exceeds the maximum range of +127).
PastPaper.question 19 · short_answer
2 PastPaper.marks
Convert the hexadecimal number \(9\text{C}\) into an 8-bit signed two's complement binary integer, and then state its equivalent denary value.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Convert the hexadecimal characters to 4-bit binary values: \(9 = 1001\) \(\text{C} = 12 = 1100\) Combined, the 8-bit binary number is \(10011100\).
2. Convert the signed binary integer to denary: The MSB has a weight of \(-128\). \(-128 + 16 + 8 + 4 = -100\).
Alternatively, to find the magnitude: Invert the bits of \(10011100\) \(\rightarrow 01100011\) Add 1 \(\rightarrow 01100100\) (which is denary \(64 + 32 + 4 = 100\)) Since the MSB was 1, the value is \(-100\).
PastPaper.markingScheme
1 mark: Correctly converting the hexadecimal value to the 8-bit binary pattern: \(10011100\). 1 mark: Correctly calculating the denary representation of this two's complement pattern: \(-100\).
PastPaper.question 20 · short_answer
2 PastPaper.marks
Subtract the 8-bit binary integer \(00011011\) from \(01001100\) using the two's complement method. Show the two's complement of the subtrahend and your final 8-bit binary result.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Find the two's complement of the subtrahend \(00011011\): Invert all bits: \(11100100\) Add 1: \(11100101\)
2. Add this value to the first number \(01001100\): \(01001100\) + \(11100101\) ------------ \(100110001\)
Discard the carry bit from the 9th column to yield the final 8-bit result: \(00110001\).
1 mark: Correct two's complement of the subtrahend: \(11100101\). 1 mark: Correct final 8-bit binary result: \(00110001\) (ignore any 9th carry bit).
PastPaper.question 21 · theory
3.33 PastPaper.marks
An Integrated Development Environment (IDE) contains several debugging features. Describe the purpose of each of the following debugging features: (i) Breakpoint, (ii) Single-stepping, (iii) Variable watch (watchpoint).
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Breakpoint: This allows the programmer to set a specific point in the source code where execution will automatically halt. This lets the developer inspect the current state of variables and memory at that exact moment. 2. Single-stepping: This feature allows the programmer to run the program one line/instruction at a time. It is highly useful for tracing the exact execution path and seeing exactly where a logic error occurs. 3. Variable watch (watchpoint): This feature continuously monitors and displays the value of specified variables as the program runs or is stepped through. It helps detect when and how a variable's value changes unexpectedly.
PastPaper.markingScheme
1 mark for correct description of Breakpoint (halting execution at a specific line to inspect state). 1 mark for correct description of Single-stepping (executing code line-by-line to observe program flow). 1 mark for correct description of Variable watch (monitoring and displaying specific variable values during execution).
PastPaper.question 22 · theory
3.33 PastPaper.marks
Software developers frequently make use of program libraries. (a) Define what is meant by a program library. (b) Describe two benefits of using dynamic linking (dynamic link libraries) over static linking.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) A program library is a collection of pre-written, pre-compiled modules, functions, or subroutines that can be imported and reused by other software applications to perform common tasks. (b) Benefits of dynamic linking over static linking: 1. Smaller executable file size: The library code is not combined into the executable file; it remains external and is loaded only at runtime, saving disk space. 2. Independent updates: If a bug is fixed or an improvement is made in the library, the DLL file can be updated without the need to recompile or redistribute the main application. 3. Shared memory: Multiple running applications can share a single copy of the dynamic library loaded in RAM, saving system memory.
PastPaper.markingScheme
(a) 1 mark for defining a program library (pre-compiled/written reusable code/routines). (b) 2 marks for any two described benefits of dynamic linking (e.g., smaller executable size, independent updates, shared RAM). Max 2 marks.
PastPaper.question 23 · theory
3.33 PastPaper.marks
An Integrated Development Environment (IDE) provides various coding aids to assist programmers during code entry. Describe how each of the following coding aids helps a programmer: (i) Auto-completion, (ii) Syntax highlighting, (iii) Auto-indentation.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Auto-completion (or Intellisense): Predicts and displays a list of matching keywords, variables, or functions as the programmer types. Selecting from this list speeds up typing and prevents spelling/syntax mistakes. 2. Syntax highlighting: Displays different components of source code (such as language keywords, variables, strings, and comments) in different colors or fonts. This improves code readability and helps the programmer quickly identify syntax errors, such as unclosed strings or mismatched brackets. 3. Auto-indentation: Automatically formats and indents code blocks (such as inside 'if' statements or loops) according to the nesting level. This makes the logical structure and flow of the program visually clear, helping to prevent structural logic errors.
PastPaper.markingScheme
1 mark for explaining Auto-completion (speeding up entry/preventing typos by suggesting keywords/identifiers). 1 mark for explaining Syntax highlighting (color-coding elements to improve readability/spot syntax errors easily). 1 mark for explaining Auto-indentation (automatically formatting code blocks to make logical structure clear).
Paper 2 Fundamental Problem-solving and Programming Skills
Answer all questions. Refer to the enclosed insert for list of pseudocode functions.
23 PastPaper.question · 81 PastPaper.marks
PastPaper.question 1 · structured
4 PastPaper.marks
A programmer is writing a program to process student IDs. Each ID is a string in the format "YYYY-D-NNN" (e.g., "2023-F-045"), where YYYY is a 4-digit year, D is a single character department code, and NNN is a 3-digit unique number.
The following pseudocode function extracts the department code and returns the name of the department.
1. Identify the built-in pseudocode function used in this code and state its purpose. [2] 2. State the value returned by the function call `GetDepartment("2022-X-999")`. [1] 3. Identify the type of selection structure used in this function. [1]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. The built-in function used is `MID` (1 mark). Its purpose is to extract a substring of a specified length (here, 1 character) from a source string starting at a specified character index (here, position 6) (1 mark). 2. The parameter passed is `"2022-X-999"`. The character at position 6 is `'X'`. Since `'X'` does not match `'F'`, `'H'`, or `'I'`, the `OTHERWISE` path is taken, returning `"Unknown"` (1 mark). 3. The selection structure is `CASE OF ... ENDCASE` (also acceptable: case selection, multi-way branch) (1 mark).
PastPaper.markingScheme
1. Award 1 mark for correctly identifying the function as `MID`. Award 1 mark for describing its purpose (extracting a substring / specific number of characters from a starting index). 2. Award 1 mark for the exact output string `"Unknown"` (accept without quotes). 3. Award 1 mark for identifying the structure as `CASE OF`, `CASE statement`, or `multi-way selection`. Do not accept simply 'selection' or 'IF statement'.
PastPaper.question 2 · structured
4 PastPaper.marks
The following pseudocode function processes an integer value and classifies it.
```pseudocode FUNCTION ProcessNumber(Value : INTEGER) RETURNS STRING DECLARE Remainder : INTEGER IF Value <= 0 THEN RETURN "Invalid" ELSE Remainder <- Value MOD 2 IF Remainder = 0 THEN RETURN "Even" ELSE RETURN "Odd" ENDIF ENDIF ENDFUNCTION ```
Answer the following questions:
1. State the scope of the variable `Remainder`. [1] 2. Identify the nested selection block in this code. [1] 3. State the value returned by the function call `ProcessNumber(-5)`. [1] 4. Write a pseudocode statement to call `ProcessNumber` with the argument 17 and assign the result to a variable named `Result`. [1]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. The variable `Remainder` is declared inside the function using `DECLARE`, meaning it has a **local** scope and is only accessible within `ProcessNumber` (1 mark). 2. The nested selection block is the inner `IF Remainder = 0 THEN ... ELSE ... ENDIF` statement which sits entirely within the outer `ELSE` block (1 mark). 3. When the argument is \(-5\), the condition `Value <= 0` evaluates to TRUE (since \(-5 \le 0\)), so the function immediately executes `RETURN "Invalid"` (1 mark). 4. To call the function and assign its result, the correct pseudocode syntax is: `Result <- ProcessNumber(17)` (1 mark).
PastPaper.markingScheme
1. Award 1 mark for 'Local' or 'Local scope'. 2. Award 1 mark for identifying the nested selection block (accept description of the inner `IF` statement or specifying the line range containing the inner check). 3. Award 1 mark for `"Invalid"` (accept without quotes). 4. Award 1 mark for the exact statement: `Result <- ProcessNumber(17)` (allow variable spacing, but the assignment operator `<-` and spelling must be correct).
The following pseudocode function processes student exam scores stored in an array:
FUNCTION CalculatePassedAverage(Scores : ARRAY, TotalStudents : INTEGER) RETURNS REAL DECLARE Index : INTEGER DECLARE PassedCount : INTEGER DECLARE PassedSum : REAL PassedCount <- 0 PassedSum <- 0 FOR Index <- 1 TO TotalStudents IF Scores[Index] >= 50 THEN PassedCount <- PassedCount + 1 PassedSum <- PassedSum + Scores[Index] ENDIF ENDFOR IF PassedCount > 0 THEN RETURN PassedSum / PassedCount ELSE RETURN -1.0 ENDIF ENDFUNCTION
Complete the identifier table below for the variables PassedCount and PassedSum by identifying the missing entries (a) and (b).
| Identifier | Data Type | Description / Purpose | |---|---|---| | PassedCount | INTEGER | (a) | | PassedSum | (b) | To store the sum of scores that are 50 or above |
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
For (a): Analyzing the loop, when a student's score is 50 or above, 'PassedCount' incremented by 1 ('PassedCount <- PassedCount + 1'). Therefore, its purpose is to count how many students scored 50 or above / passed. For (b): Looking at the declarations at the beginning of the function, 'DECLARE PassedSum : REAL' explicitly defines the data type for 'PassedSum' as REAL.
PastPaper.markingScheme
1 mark for (a): Purpose must mention counting / storing the number of students who passed or scored 50 or above. 1 mark for (b): REAL (Accept case-insensitive 'Real'. Reject 'Float', 'Double', or 'Decimal' as they are not standard Cambridge pseudocode data types).
PastPaper.question 4 · Flowchart Construction
5 PastPaper.marks
An algorithm is designed to calculate the total cost of a customer order, including delivery fees. The rules are as follows: 1. Input the order value (OrderValue) and whether the customer has a loyalty card (HasCard, which is Boolean: TRUE or FALSE). 2. If OrderValue is greater than or equal to $50, delivery is free (DeliveryCost is 0). 3. If OrderValue is less than $50, the standard delivery cost is $5. 4. If the standard delivery cost of $5 applies AND the customer has a loyalty card (HasCard is TRUE), they receive a $2 discount on the delivery cost (making it $3). 5. The total cost (TotalCost) is calculated as the sum of OrderValue and DeliveryCost. 6. Output TotalCost.
A programmer starts to draw a flowchart for this algorithm but leaves five symbols incomplete, labelled A, B, C, D, and E. - A is a decision diamond (checking if the order qualifies for free delivery on the 'Yes' branch, or standard delivery on the 'No' branch). - B is a process rectangle (assigning standard delivery cost to DeliveryCost). - C is a decision diamond (checking if the loyalty card discount applies on the 'Yes' branch). - D is a process rectangle (adjusting the DeliveryCost with the discount on the 'Yes' branch of decision C). - E is a process rectangle (calculating the total cost).
Identify the correct expression, decision, or statement to complete each label.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Step 1: Check the condition for free delivery. The threshold is $50. If OrderValue >= 50, the delivery is free. Thus, Decision A must check if \(OrderValue \ge 50\). Step 2: If the condition is False (No branch), the standard delivery cost of $5 is assigned. Thus, Process B must be \(DeliveryCost \leftarrow 5\). Step 3: After assigning the standard delivery, we check if the customer has a loyalty card to apply a discount. Thus, Decision C must check if \(HasCard = \text{TRUE}\). Step 4: If Decision C is True (Yes branch), the delivery cost receives a $2 discount, reducing it from $5 to $3. Thus, Process D must assign \(DeliveryCost \leftarrow 3\) or \(DeliveryCost \leftarrow DeliveryCost - 2\). Step 5: Before outputting, the final total cost must be calculated by adding the order value and delivery cost. Thus, Process E must be \(TotalCost \leftarrow OrderValue + DeliveryCost\).
PastPaper.markingScheme
1 mark per correct block: - A: OrderValue >= 50 (accept: OrderValue > 49.99, or equivalent logic check) - B: DeliveryCost <- 5 (accept assignment with <- or =) - C: HasCard = TRUE (accept: HasCard? or HasCard = TRUE?) - D: DeliveryCost <- 3 or DeliveryCost <- DeliveryCost - 2 (accept assignment with <- or =) - E: TotalCost <- OrderValue + DeliveryCost (accept assignment with <- or =)
PastPaper.question 5 · Flowchart to Pseudocode Conversion
5 PastPaper.marks
A programmer has designed an algorithm to calculate the average of a series of positive numeric values entered by a user. The user enters -1 to signal the end of the input sequence.
Here is the description of the flowchart nodes and their connections:
1. START 2. Process: Count ← 0, Total ← 0 3. Input: INPUT Value 4. Decision: Is Value = -1? - If NO: 5. Process: Total ← Total + Value 6. Process: Count ← Count + 1 7. Input: INPUT Value 8. (Loop back to Decision Node 4) - If YES: 9. Decision: Is Count > 0? - If YES: 10. Process: Average ← Total / Count 11. Output: OUTPUT Average 12. (Proceed to END Node 14) - If NO: 13. Output: OUTPUT "No data" 14. (Proceed to END Node 14) 14. END
Write the equivalent pseudocode for this flowchart using standard Cambridge international pseudocode syntax.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To convert the flowchart to pseudocode, we follow the logical blocks: 1. Initialize variables: Set both `Count` and `Total` to `0` and take the first `INPUT Value` before entering the loop. 2. Design the loop: The loop runs as long as `Value` is not equal to `-1` (`Value <> -1`). A pre-assertion `WHILE` loop is the most direct fit here. 3. Inside the loop: Add the current `Value` to `Total`, increment `Count` by `1`, and read the next `INPUT Value` so the loop termination condition can be checked again. 4. Design the conditional check after the loop: If `Count > 0`, calculate `Average` as `Total / Count` and output it. Otherwise, output "No data" to avoid a division-by-zero error.
PastPaper.markingScheme
Award up to 5 marks based on the following criteria: - 1 mark: Initializing variables `Count` and `Total` to 0, AND taking the initial input `Value` before the loop. - 1 mark: Using a correct loop structure with the condition to terminate when `Value` is `-1` (e.g., `WHILE Value <> -1` ... `ENDWHILE` or equivalent nested structure). - 1 mark: Correct processing inside the loop: accumulating `Total`, incrementing `Count`, and requesting the next `Value` inside the loop body. - 1 mark: Correct conditional structure (`IF Count > 0 THEN ... ELSE ... ENDIF`) to check that at least one value was entered before division. - 1 mark: Correct calculation of `Average` and output of either `Average` or `"No data"` based on the conditional branch.
PastPaper.question 6 · text
3 PastPaper.marks
Write pseudocode to define a record type BookRecord with the following fields: BookID (integer), Title (string), and IsBorrowed (boolean). Then, write a pseudocode statement to declare a 1-dimensional array LibraryCatalog of 1000 elements of type BookRecord, indexed from 1 to 1000.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To define a composite data type, use the TYPE ... ENDTYPE structure. Inside the structure, declare each field with its respective identifier and data type. To declare the array, use the DECLARE keyword followed by the identifier, a colon, the ARRAY keyword with the bounds, and the OF keyword followed by the user-defined type name. Code: TYPE BookRecord DECLARE BookID : INTEGER DECLARE Title : STRING DECLARE IsBorrowed : BOOLEAN ENDTYPE DECLARE LibraryCatalog : ARRAY[1:1000] OF BookRecord
PastPaper.markingScheme
1 Mark: Correct record definition structure using TYPE BookRecord and ENDTYPE. 1 Mark: All three fields correctly declared within the record structure with their specified data types. 1 Mark: Correct declaration of the 1D array including identifier, bounds [1:1000], and correct user-defined base type.
PastPaper.question 7 · text
3 PastPaper.marks
A parking garage consists of 5 floors with 50 parking spaces on each floor. Write pseudocode to define a record type CarDetails with the fields RegPlate (string) and HoursParked (integer). Then, declare a 2-dimensional array GarageGrid of type CarDetails to represent all the parking spaces in the garage (using 1 to 5 for floors and 1 to 50 for spaces).
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
First, define the record type CarDetails with fields RegPlate (STRING) and HoursParked (INTEGER) within a TYPE ... ENDTYPE block. Second, declare a 2D array named GarageGrid with index bounds 1 to 5 and 1 to 50, where each element is of the composite type CarDetails.
PastPaper.markingScheme
1 Mark: Correct definition of TYPE CarDetails and ENDTYPE with appropriate field declarations. 1 Mark: Correct 2-dimensional array declaration syntax. 1 Mark: Correct bounds [1:5, 1:50] and data type OF CarDetails.
PastPaper.question 8 · short-answer
3 PastPaper.marks
A programmer is developing a system to manage a local tennis club's membership database. For each member, the system needs to store their unique MemberID (integer), Name (string), MembershipType (string), and BalanceOwed (real).
The programmer decides to implement this by declaring a 1D array of records, rather than using four separate 1D (parallel) arrays.
Explain three advantages of using a 1D array of records instead of multiple parallel arrays to store this data.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Using a 1D array of records offers several distinct advantages over parallel arrays: - **Data Integrity/Alignment**: With parallel arrays, if you sort or delete an element in one array, you must perform the exact same action at the exact same index in all other three arrays. Failure to do so leads to mismatched member data. With a record, all attributes are bound together, so moving one record keeps all associated data together. - **Subroutine Parameters**: Modularity is improved. A procedure to process a member's payment only needs to accept one parameter of the record type, rather than multiple parameters for each attribute. - **Extensibility**: If the club decides to store a fifth attribute (e.g., DateJoined), the programmer only needs to modify the record structure definition. With parallel arrays, a fifth array must be declared, and all array manipulation logic across the program must be updated.
PastPaper.markingScheme
Award 1 mark for each valid advantage explained, up to a maximum of 3 marks: - **Preventing data misalignment**: Easier to sort/delete/insert data because you only need to swap/manipulate one record index instead of keeping four separate arrays aligned. - **Simplified modularity**: A single record or the array of records can be passed to subroutines as a single parameter rather than passing multiple parallel arrays/variables. - **Ease of maintenance / Extensibility**: Adding a new attribute only requires changing the record definition, rather than declaring a new parallel array and rewriting related indexing code. - **Improved readability / Conceptual logic**: The data structure matches the real-world entity (a member) more logically, making the code easier to understand and debug.
*Note: Do not accept vague answers like "it is faster" or "it takes less memory" unless qualified by specific logic showing why management overhead is reduced.*
PastPaper.question 9 · Pseudocode
5 PastPaper.marks
Write a pseudocode function IsValidTriangle which receives three real values representing the lengths of three sides of a shape. The function must return TRUE if these three sides can form a valid triangle, and FALSE otherwise.
Note that for three sides to form a valid triangle, all sides must be strictly greater than zero, and the sum of any two sides must be strictly greater than the third side.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
An elegant solution checks both constraints: that all side lengths are positive numbers, and that they satisfy the triangle inequality theorem (the sum of any two sides must be strictly greater than the remaining side).
Example Pseudocode: FUNCTION IsValidTriangle(Side1 : REAL, Side2 : REAL, Side3 : REAL) RETURNS BOOLEAN IF Side1 > 0 AND Side2 > 0 AND Side3 > 0 THEN IF (Side1 + Side2 > Side3) AND (Side1 + Side3 > Side2) AND (Side2 + Side3 > Side1) THEN RETURN TRUE ELSE RETURN FALSE ENDIF ELSE RETURN FALSE ENDIF ENDFUNCTION
PastPaper.markingScheme
Award up to 5 marks: 1 mark: Correct FUNCTION header defining three parameters of REAL data type and returning a BOOLEAN type. 1 mark: Correct validation that all three sides are strictly positive (Side1 > 0 AND Side2 > 0 AND Side3 > 0). 2 marks: Correct implementation of the triangle inequality rules (sum of any two sides must be greater than the third). Award 1 mark if only some pairs are checked, or if OR is incorrectly used instead of AND. 1 mark: Correct RETURN statements for both valid and invalid scenarios and correct ENDFUNCTION termination.
PastPaper.question 10 · Program Error Identification
2 PastPaper.marks
The following pseudocode function `FindMinimum` is designed to find and return the smallest positive integer in an array of 50 positive integers.
``` 01 FUNCTION FindMinimum(List : ARRAY[1:50] OF INTEGER) RETURNS INTEGER 02 DECLARE Index : INTEGER 03 DECLARE MinValue : INTEGER 04 MinValue <- 0 05 FOR Index <- 1 TO 50 06 IF List[Index] < MinValue THEN 07 MinValue <- List[Index] 08 ENDIF 09 ENDFOR 10 RETURN MinValue 11 ENDFUNCTION ```
Identify the line number that contains the logic error and write the corrected pseudocode statement for this line.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Line 04 contains the logic error. It initializes `MinValue` to 0. Since the array contains only positive integers, no elements will ever be strictly less than 0. Consequently, the conditional test on line 06 will always evaluate to FALSE, and the function will incorrectly return 0. To fix this, `MinValue` should be initialized to the first element in the array (`List[1]`) or a very large sentinel value.
PastPaper.markingScheme
1 mark: Correctly identifying line 04 (or line 4). 1 mark: Providing a correct replacement statement, such as `MinValue <- List[1]` (accept `MinValue <- List[Index]` if logic is clear, or initializing to a large constant integer value).
PastPaper.question 11 · Program Error Identification
2 PastPaper.marks
The following pseudocode function `FindChar` is designed to search for the first occurrence of a character `TargetChar` in a string `SearchStr` and return its 1-based index position. If the character is not found, the function must return -1.
``` 01 FUNCTION FindChar(SearchStr : STRING, TargetChar : CHAR) RETURNS INTEGER 02 DECLARE Index : INTEGER 03 DECLARE Found : BOOLEAN 04 Found <- FALSE 05 Index <- 1 06 WHILE (Index <= LENGTH(SearchStr)) AND (Found = FALSE) 07 IF SUBSTRING(SearchStr, Index, 1) = TargetChar THEN 08 Found <- TRUE 09 ENDIF 10 Index <- Index + 1 11 ENDWHILE 12 IF Found = TRUE THEN 13 RETURN Index 14 ELSE 15 RETURN -1 16 ENDIF 17 ENDFUNCTION ```
Identify the line number that contains the logic error and write the corrected pseudocode statement for this line.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The logic error is on line 13. When the `TargetChar` is found on line 07, `Found` is set to TRUE. However, line 10 (`Index <- Index + 1`) still executes before the loop terminates on the next condition check. This increments `Index` to one position past the match. Thus, line 13 returns an incorrect, offset index. Returning `Index - 1` corrects this offset.
PastPaper.markingScheme
1 mark: Correctly identifying line 13. 1 mark: Providing a correct replacement statement, such as `RETURN Index - 1`.
PastPaper.question 12 · Program Error Identification
2 PastPaper.marks
The following pseudocode procedure `Swap` is designed to exchange the values of two integer parameters passed by reference.
Identify the line number that contains the logic error and write the corrected pseudocode statement for this line.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The logic error occurs on line 05. At line 04, `Value1` is overwritten with the value of `Value2`. When line 05 executes, assigning `Value1` back to `Value2` simply duplicates the current value of `Value1` (which is `Value2`), failing to restore the original value of `Value1`. Line 05 must instead assign the saved value stored in the variable `Temp` to `Value2`.
PastPaper.markingScheme
1 mark: Correctly identifying line 05 (or line 5). 1 mark: Providing the correct replacement statement `Value2 <- Temp`.
PastPaper.question 13 · pseudocode
7 PastPaper.marks
A programmer is developing a text editing application and needs a function CleanString() to sanitize user input. The function must accept a string InString as a parameter and return a new string with: 1. All leading spaces (at the start of the string) removed. 2. All trailing spaces (at the end of the string) removed. 3. All multiple consecutive spaces between words reduced to a single space. For example, if the input is " Hello World ", the returned string must be "Hello World". If the input string is empty or contains only spaces, the function must return an empty string "". Write a pseudocode algorithm for the function CleanString(). You must use the following built-in functions: * LENGTH(s : STRING) RETURNS INTEGER: returns the number of characters in string s. * SUBSTR(s : STRING, start : INTEGER, length : INTEGER) RETURNS STRING: returns a substring of length characters starting at position start (indices start at 1). * String concatenation is performed using the & operator.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The algorithm works by: 1. Calculating the length of InString. 2. Using a WHILE loop to find the index of the first non-space character (StartPtr). 3. Checking if StartPtr exceeds the length, meaning the string is empty or contains only spaces, and returning "" if true. 4. Using a WHILE loop searching backwards from the end of InString to find the index of the last non-space character (EndPtr). 5. Initializing an empty OutString and iterating from StartPtr to EndPtr. During each iteration, the character at index i is checked. It is appended to OutString only if both it and the previously processed character are not spaces, effectively collapsing multiple internal spaces into a single space. Finally, OutString is returned.
PastPaper.markingScheme
Award up to 7 marks for correct pseudocode: 1 mark: Correct function header with parameter, return type, and matching ENDFUNCTION. 1 mark: Correct loop/logic to find the index of the first non-space character (StartPtr) to strip leading spaces. 1 mark: Correct check for boundary condition when string is empty or only spaces (returning ""). 1 mark: Correct loop/logic to find the index of the last non-space character (EndPtr) from the right to strip trailing spaces. 1 mark: Correct loop structure starting from StartPtr to EndPtr. 1 mark: Correct condition inside the loop to prevent appending a space if the previous appended character was also a space. 1 mark: Correct string concatenation and updating tracking variables correctly inside the loop, followed by returning the built string.
PastPaper.question 14 · Alternative Storage Optimization Queries
1 PastPaper.marks
A programmer defines a record type to store student data. The original design uses a 6-character string to represent `StudentID` (where 1 character = 1 byte). To optimize storage, the programmer decides to store `StudentID` as an Integer (which requires 4 bytes of storage). Calculate the total saving in bytes if a file contains 10,000 of these student records.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
First, find the storage saving per record: \(6\text{ bytes} - 4\text{ bytes} = 2\text{ bytes saved per record}\).
Next, multiply the saving per record by the total number of records: \(2\text{ bytes} \times 10,000 = 20,000\text{ bytes}\).
PastPaper.markingScheme
1 mark for the correct calculation and final value of 20000 (or 20,000).
PastPaper.question 15 · Alternative Storage Optimization Queries
1 PastPaper.marks
An array contains 1,000 Boolean elements. In a certain system, a standard Boolean variable occupies 1 byte of memory. To optimize storage, a programmer decides to use bit packing, where each Boolean value is stored as a single bit within a byte. State the number of bytes saved by using this optimized bit-packing method to store all 1,000 elements.
1 mark for the correct calculation showing 875 bytes saved.
PastPaper.question 16 · Alternative Storage Optimization Queries
1 PastPaper.marks
A text file stores 500 usernames. Under Option A, each username is stored as a fixed-length field of 20 characters (1 byte per character). Under Option B, each username is stored as a variable-length field using its actual length plus 1 overhead byte to store the field's length. If the average length of a username is 12 characters, calculate the storage space saved in bytes for the entire file by choosing Option B instead of Option A.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Calculate total size for Option A: \(500\text{ records} \times 20\text{ bytes/record} = 10,000\text{ bytes}\).
2. Calculate total size for Option B: Average size per record = \(12\text{ bytes (characters)} + 1\text{ byte (overhead)} = 13\text{ bytes}\). Total average size for Option B = \(500\text{ records} \times 13\text{ bytes/record} = 6,500\text{ bytes}\).
1 mark for the correct final answer of 3500 (or 3,500).
PastPaper.question 17 · short answer
3 PastPaper.marks
A software developer is creating a student registration and grading system for a school. The developer decides to use decomposition during the design stage. State three advantages of decomposing this system into sub-modules.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Decomposition involves breaking a complex system into smaller, self-contained sub-modules. The key advantages are: 1. Teamwork and Parallel Development: Different developers can work on different modules at the same time. 2. Simplified Testing: Modules can be unit-tested individually, making debugging much easier. 3. Reusability: Well-defined modules can be reused within this system or in future projects.
PastPaper.markingScheme
Award 1 mark for each valid advantage, up to a maximum of 3: - Division of labor / multiple programmers can work simultaneously on different modules; - Easier to test and debug individual modules; - Code reusability / modules can be reused in other programs; - Simplifies maintenance as updates can be localized; - Reduces complexity / makes the project easier to understand.
PastPaper.question 18 · written
3 PastPaper.marks
A state-transition diagram is designed to parse a sequence of characters containing only 'A' and 'B'.
- The system starts in state S1. - If the system is in state S1 and receives 'A', it transitions to S2. If it receives 'B', it remains in S1. - If the system is in state S2 and receives 'A', it transitions to S3. If it receives 'B', it transitions to S3. - If the system is in state S3 and receives 'A', it transitions to S1. If it receives 'B', it transitions to S2.
Complete the state-transition table below by identifying the next state for the three missing transitions (labelled X, Y, and Z):
| Current State | Input 'A' | Input 'B' | | :--- | :--- | :--- | | S1 | S2 | X | | S2 | Y | S3 | | S3 | S1 | Z |
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Based on the rules provided in the scenario: 1. For transition X (Current State: S1, Input: 'B'): The rule states 'If it receives 'B', it remains in S1.' Therefore, X is S1. 2. For transition Y (Current State: S2, Input: 'A'): The rule states 'If the system is in state S2 and receives 'A', it transitions to S3.' Therefore, Y is S3. 3. For transition Z (Current State: S3, Input: 'B'): The rule states 'If the system is in state S3 and... if it receives 'B', it transitions to S2.' Therefore, Z is S2.
PastPaper.markingScheme
1 mark for identifying X = S1 1 mark for identifying Y = S3 1 mark for identifying Z = S2
PastPaper.question 19 · written
3 PastPaper.marks
A state machine parses a simple numeric representation string. The transition rules are as follows: - S1 is the start state. - If a sign ('+' or '-') is read from S1, the state transitions to S2. - If a digit ('0'-'9') is read from S1, S2, or S3, the state transitions to S3. - Any other input (such as alphabetic characters) from any state transitions the system to the error state S4. Once in S4, any further input remains in S4.
Identify the state of the machine after parsing each of the following parts of the input string "+42A" starting from S1: 1. After processing the first character '+' 2. After processing the first three characters '+42' 3. After processing the entire string '+42A'
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Let's trace the execution step-by-step starting from S1: - The first character is '+'. A transition from S1 on a sign character ('+' or '-') goes to S2. Thus, after '+', the state is S2. - The next character is '4'. A transition from S2 on a digit goes to S3. - The third character is '2'. A transition from S3 on a digit goes to S3. Thus, after '+42', the state is S3. - The final character is 'A'. Any non-digit/non-sign character transitions the system to the error state S4 from any state. Thus, after '+42A', the state is S4.
PastPaper.markingScheme
1 mark for stating S2 for part 1 1 mark for stating S3 for part 2 1 mark for stating S4 for part 3
PastPaper.question 20 · short_answer
2 PastPaper.marks
During the design stage of a software development project, a systems analyst decomposes a complex system into smaller, manageable modules. Explain two benefits of dividing a program into modules before implementation begins.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Decomposing a system into modules provides several key benefits: First, it enables parallel development, meaning multiple programmers can write and test different modules at the same time, significantly speeding up the project timeline. Second, it facilitates easier testing and debugging, as each module can be isolated and verified independently (unit testing) to ensure correctness before being combined into the larger system. Third, it promotes code reusability, allowing a single module to be invoked multiple times across different parts of the program or even reused in future projects, which reduces code duplication.
PastPaper.markingScheme
Award 1 mark for each valid explained benefit up to a maximum of 2 marks. Acceptable points include: 1. Division of labor / Parallel development: Different programmers can work on different modules at the same time to speed up development. 2. Easier testing and debugging: Individual modules can be tested and debugged independently (unit testing) before integration. 3. Code reusability: Modules can be reused in other parts of the application or in different systems. 4. Manageability / Maintenance: Reduces complexity, making the code easier to understand, maintain, and update in the future.
PastPaper.question 21 · pseudocode
6 PastPaper.marks
An algorithm is required to clean a text sentence by removing unnecessary characters and formatting spaces.
Write pseudocode for the function `CleanSentence` which takes a string `InputStr` as a parameter and returns the cleaned string.
The function must process `InputStr` and apply the following cleaning rules: 1. Only uppercase letters ('A' to 'Z'), lowercase letters ('a' to 'z'), and space characters (' ') are allowed in the output string. All other characters must be removed. 2. There must be no consecutive space characters in the output string (i.e. multiple spaces are reduced to a single space). 3. There must be no leading space (a space at the very start) or trailing space (a space at the very end) in the output string.
You must use the following pseudocode built-in functions: * `LENGTH(ThisString : STRING) RETURNS INTEGER` - returns the number of characters in the string. * `MID(ThisString : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING` - returns a sub-string of a given length starting from the specified index (1-based index).
Cleaned <-- "" PrevChar <-- ' ' // Initialised to space to automatically prevent leading spaces
FOR i <-- 1 TO LENGTH(InputStr) NextChar <-- MID(InputStr, i, 1)
// Check if the character is alphabetical IF (NextChar >= 'a' AND NextChar <= 'z') OR (NextChar >= 'A' AND NextChar <= 'Z') THEN Cleaned <-- Cleaned & NextChar PrevChar <-- NextChar ELSEIF NextChar = ' ' THEN // Append space only if the last appended character was not a space IF PrevChar <> ' ' THEN Cleaned <-- Cleaned & ' ' PrevChar <-- ' ' ENDIF ENDIF NEXT i
// Remove trailing space if there is one IF LENGTH(Cleaned) > 0 THEN IF MID(Cleaned, LENGTH(Cleaned), 1) = ' ' THEN Cleaned <-- MID(Cleaned, 1, LENGTH(Cleaned) - 1) ENDIF ENDIF
RETURN Cleaned ENDFUNCTION ```
PastPaper.markingScheme
Award up to 6 marks for correct logic:
1. **Function Definition & Return**: Correct function header (defining `InputStr : STRING` as a parameter and returning `STRING`) and corresponding `RETURN` and `ENDFUNCTION`. (1 mark) 2. **Iteration**: Loop starts correctly at index 1 and ends at `LENGTH(InputStr)`. (1 mark) 3. **Character Extraction**: Uses standard `MID(InputStr, i, 1)` to extract each individual character. (1 mark) 4. **Alphabet Validation**: Correct checking and appending of alphabetic characters ('a'..'z' and 'A'..'Z'). (1 mark) 5. **Consecutive & Leading Spaces**: Avoids consecutive space characters and leading spaces (e.g. by tracking the previous character/state or comparing carefully). (1 mark) 6. **Trailing Space Removal**: Correctly checks if the final character is a space and removes it from the final returned string. (1 mark)
PastPaper.question 22 · pseudocode
6 PastPaper.marks
PastPaper.question 23 · free_text
8 PastPaper.marks
A school library stores details of student textbook loans in a text file named `Loans.txt`.
Each line of the text file represents a single loan record of exactly 25 characters, structured with fixed-width fields separated by commas as follows: * Characters 1 to 7: Student ID (e.g. `STU4412`) * Character 8: Comma (`,`) * Characters 9 to 14: Book ID (e.g. `BK9012`) * Character 15: Comma (`,`) * Characters 16 to 25: Due Date in format `YYYY-MM-DD` (e.g. `2023-11-25`)
An example of one line in the file: `STU4412,BK9012,2023-11-25`
Write pseudocode for a procedure, `GenerateOverdueReport`, which: * receives a parameter `CurrentDate` of type `STRING` (containing a date formatted as `YYYY-MM-DD`) * reads all records from `Loans.txt` * identifies all loans where the `DueDate` is chronologically before the `CurrentDate` (this comparison can be performed directly on the strings due to the ISO date format) * writes a line to a new text file, `OverdueReport.txt`, for each overdue loan in the format: ` overdue for ` * writes a final summary line to `OverdueReport.txt` showing the total count of overdue books in the format: `Total overdue: ` * closes both files.
You should assume that the text file `Loans.txt` exists and contains at least one record. You must use the following standard pseudocode functions for string manipulation: * `MID(ThisString : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING` * `NUM_TO_STR(ThisNum : INTEGER) RETURNS STRING`
// Check if date is overdue IF DateDue < CurrentDate THEN WRITEFILE "OverdueReport.txt", StudentID & " overdue for " & BookID OverdueCount <- OverdueCount + 1 ENDIF ENDWHILE
// Write the final summary line WRITEFILE "OverdueReport.txt", "Total overdue: " & NUM_TO_STR(OverdueCount)
Award 1 mark for each of the following (max 8 marks): 1. **Procedure Header & Parameter:** Correct procedure header with parameter name and data type (`CurrentDate : STRING`) and matching `ENDPROCEDURE`. 2. **File Operations (Open):** Correctly opening `Loans.txt` for reading and `OverdueReport.txt` for writing. 3. **Looping Logic:** Use of a loop until the end of `Loans.txt` is reached (`WHILE NOT EOF(...)` or equivalent loop structure). 4. **Reading File:** Reading a record/line from `Loans.txt` into a string variable inside the loop. 5. **String Extraction (MID):** Correctly extracting all three parts of the line (`StudentID`, `BookID`, `DateDue`) using `MID` with accurate parameters: - `StudentID`: `MID(Line, 1, 7)` - `BookID`: `MID(Line, 9, 6)` - `DateDue`: `MID(Line, 16, 10)` 6. **Overdue Condition:** Correct comparison (`DateDue < CurrentDate`) and incrementing an integer counter initialization/logic. 7. **File Writing:** Correctly writing the transaction details in the exact format ` overdue for ` to `OverdueReport.txt` inside the loop. 8. **Summary & Close:** Correctly writing the summary line with `NUM_TO_STR(OverdueCount)` to `OverdueReport.txt` *after* the loop and closing both files.