An original Thinka practice paper modelled on the structure and difficulty of the Jun 2023 (V1) Cambridge International A Level Computer Science (9618) paper. Not affiliated with or reproduced from Cambridge.
Paper 1 Theory Fundamentals
Answer all questions. Calculators are not allowed. Write in dark blue or black pen.
26 PastPaper.question · 68 PastPaper.marks
PastPaper.question 1 · Short Answer & Definition
2.5 PastPaper.marks
Define the term 'sampling resolution' as used in digital audio recording, and explain how increasing the sampling resolution affects both the quality of the sound and the file size.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Sampling resolution, also known as bit depth, refers to the number of bits assigned to encode the amplitude of each individual audio sample. When the sampling resolution is increased, the precision with which the sound wave's amplitude is recorded increases. This results in a higher dynamic range and less quantization noise, thereby improving the overall quality of the reproduced sound. However, because more bits are required to store each sample, the total amount of data generated per second of audio increases, which directly results in a larger file size.
PastPaper.markingScheme
1 mark for a correct definition of sampling resolution (number of bits per sample to represent amplitude). 1 mark for explaining the impact on quality (more precise reproduction of the wave / less quantization error / higher dynamic range). 0.5 marks for stating the impact on file size (larger file size because more data/bits must be stored per sample).
PastPaper.question 2 · Short Answer & Definition
2.5 PastPaper.marks
Explain the difference between a public IP address and a private IP address, and state how a device with a private IP address can communicate with an external server on the global internet.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A public IP address is assigned by an ISP and is unique across the entire global internet, allowing direct routing of packets. A private IP address is assigned by a local router (e.g., via DHCP) and is only unique within that specific local area network (LAN); it cannot be routed across the public internet. To allow a device with a private IP address to communicate with an external server, a router uses Network Address Translation (NAT) to translate the private IP address into the router's public IP address before forwarding packets to the internet.
PastPaper.markingScheme
1 mark for defining public IP addresses (globally unique and routable on the internet). 1 mark for defining private IP addresses (unique only within a LAN, not directly routable on the internet). 0.5 marks for identifying Network Address Translation (NAT) as the translation mechanism used by the router.
PastPaper.question 3 · Short Answer & Definition
2.5 PastPaper.marks
Describe the physical construction of a resistive touchscreen and explain how it detects a touch event.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A resistive touchscreen is constructed using two thin, transparent layers of conductive material (such as Indium Tin Oxide) separated by a small air gap or microscopic spacer dots. The top layer is flexible, while the bottom layer is rigid (often made of glass). When a finger or stylus exerts pressure on the outer surface, the flexible top layer bends and physically makes contact with the bottom layer, completing an electrical circuit at that precise point. This contact alters the electrical resistance and changes the voltage at that location. An internal controller measures this change in electrical current/voltage along both horizontal and vertical axes to determine the exact coordinate coordinates (X, Y) of the touch.
PastPaper.markingScheme
1 mark for describing the physical layers (two conductive/resistive layers separated by an air gap or spacer dots, with a flexible top layer). 1 mark for explaining the physical contact mechanism (pressure causes the layers to touch, completing a circuit). 0.5 marks for explaining how the position is determined (measuring the change in voltage/current to calculate the coordinates).
PastPaper.question 4 · Short Answer & Definition
2.5 PastPaper.marks
Describe the execution process of an interpreter when running a high-level language program, and state one disadvantage of an interpreter compared to a compiler during execution.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
An interpreter reads high-level source code and translates it into intermediate code or machine instructions one statement or line at a time, immediately executing that statement before moving on to the next. It does not produce an independent executable file. A key disadvantage of this approach during execution is that interpreted programs run significantly slower than compiled ones. This is because translation must occur dynamically on-the-fly, meaning that statements within loops are translated repeatedly every time the loop iterates, adding massive runtime overhead.
PastPaper.markingScheme
1 mark for describing the translation and execution process (translates and executes source code line-by-line / statement-by-statement). 1 mark for stating the disadvantage (slower execution speed due to real-time translation / overhead of translating loop bodies repeatedly). 0.5 marks for noting the absence of an independent executable file (which requires the interpreter to be present at runtime).
PastPaper.question 5 · Short Answer & Definition
2.5 PastPaper.marks
Explain the difference between data validation and data verification, and provide one specific example of a validation check that could be performed on a user's date of birth input.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Data validation is an automated check performed by software to ensure that the input data is sensible, reasonable, complete, and conforms to predefined rules or constraints before it is processed. Data verification, on the other hand, is a process used to ensure that data has been entered or copied accurately without errors from the original source document (such as double-keying or visual checks). For a date of birth input, a suitable validation check is a range check (e.g., verifying that the birth year is between 1900 and the current year) or a format check (e.g., ensuring the date follows the DD/MM/YYYY format).
PastPaper.markingScheme
1 mark for explaining data validation (automated software check for correctness against rules/reasonableness). 1 mark for explaining data verification (checking if data matches the source accurately / checking for transcription errors). 0.5 marks for providing a valid validation check example for date of birth (e.g., range check for year, format check for DD/MM/YYYY, or type check for numeric values).
PastPaper.question 6 · Short Answer & Definition
2.5 PastPaper.marks
Explain the key characteristics of Shareware, and how it differs from Freeware.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Shareware is a software distribution model where users are allowed to try the software free of charge for a limited trial period or with restricted features. To continue using the software after the trial expires or to unlock full features, users must pay a license fee. In contrast, Freeware is software that is provided completely free of charge with no time limits or feature restrictions. Although both are free to obtain initially, the key difference is that Shareware eventually requires payment for complete or continued usage, whereas Freeware never charges a fee, even though the source code remains closed and copyrighted.
PastPaper.markingScheme
1 mark for describing the characteristics of Shareware (distributed free on a trial basis / has time limits or limited features / requires payment to unlock full version). 1 mark for describing Freeware (distributed free of charge with no charge for usage or time limits / retains copyright). 0.5 marks for clarifying the difference regarding the payment requirement (shareware transitions to a paid model, freeware remains free).
PastPaper.question 7 · Short Answer & Definition
2.5 PastPaper.marks
Define the terms 'primary key' and 'foreign key' in a relational database, and explain how they are used together to link tables.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
In a relational database, a primary key is a field (or combination of fields) that uniquely identifies each record/row within a database table. A foreign key is a field in one database table that points to or references the primary key of another table. To establish a relationship between two tables (typically a one-to-many relationship), the primary key of the parent table is copied and stored as a foreign key attribute in the child table. This link allows the DBMS to join records across both tables while maintaining referential integrity.
PastPaper.markingScheme
1 mark for defining a primary key (a field/attribute that uniquely identifies each record in a table). 1 mark for defining a foreign key (a field in a table that references the primary key of another table). 0.5 marks for explaining how they link tables (by placing the primary key from the 'one' table as a foreign key in the 'many' table to create a relationship).
PastPaper.question 8 · Short Answer & Definition
2.5 PastPaper.marks
Explain the functions of the Program Counter (PC) and the Memory Address Register (MAR) during the fetch stage of the Fetch-Execute cycle.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
During the fetch stage, the Program Counter (PC) acts as a register holding the memory address of the next instruction scheduled for execution. The Memory Address Register (MAR) is a register that holds the physical memory address that the CPU wants to read from or write to. At the start of the fetch cycle, the address stored in the PC is copied into the MAR. The CPU then reads the instruction from RAM at the address contained in the MAR. Simultaneously, the PC is incremented to point to the address of the next sequential instruction.
PastPaper.markingScheme
1 mark for defining the role of the Program Counter (holds the address of the next instruction to be fetched). 1 mark for defining the role of the Memory Address Register (holds the address of the current memory location being read from or written to). 0.5 marks for describing their interaction during the fetch stage (the address in the PC is copied into the MAR to initiate the read operation).
PastPaper.question 9 · Short Answer
2.5 PastPaper.marks
Explain how the most significant bit (MSB) in an 8-bit signed two's complement integer affects its value, and state the lowest denary value that can be represented using this format.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. The MSB in an 8-bit signed integer has a place value of \(-128\) (or \(-2^7\)). If it is set to 1, this negative value is included in the representation, which is why a leading 1 represents a negative number. 2. The lowest denary value occurs when the MSB is 1 and all other bits are 0 (i.e., \(10000000_2\)), which represents \(-128\).
PastPaper.markingScheme
Award marks as follows: - 1 mark: Identifying that the MSB has a negative place value of \(-128\) (or \(-2^{n-1}\) generally). - 0.5 marks: Describing that if the MSB is 1, the number is negative, and if it is 0, the value is positive. - 1 mark: Stating that the lowest denary value that can be represented is \(-128\). (Maximum 2.5 marks)
PastPaper.question 10 · Short Answer
2.5 PastPaper.marks
In a local area network (LAN), two common architectures are peer-to-peer and client-server. Identify two key differences between these architectures in terms of data storage and security administration.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Data Storage: In a client-server setup, files and applications are stored on a centralized server, making backups and access control easier to manage. In peer-to-peer, files are distributed across the individual hard drives of the connected computers. 2. Security Administration: Client-server security is centralized; a network administrator manages user permissions, access rights, and password policies from the server. In peer-to-peer, security is decentralized; individual users must set access controls and permissions for their own shared directories.
PastPaper.markingScheme
Award marks as follows: - 1 mark: Explaining the difference in data storage (centralized server vs. distributed among individual nodes). - 1 mark: Explaining the difference in security administration (centralized administration by a network admin vs. user-managed/decentralized security). - 0.5 marks: Providing a clear, coherent contrast that accurately distinguishes between both architectures. (Maximum 2.5 marks)
PastPaper.question 11 · Short Answer
2.5 PastPaper.marks
During the instruction cycle, the CPU may receive an interrupt. Describe how the Program Counter (PC) and other register contents are preserved when an interrupt is serviced, and how they are restored afterwards.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Saving state: When an interrupt is accepted, the CPU completes its current execution cycle. The current contents of the Program Counter (PC) and other registers are pushed (saved) onto a system stack. 2. Restoring state: Once the Interrupt Service Routine (ISR) has completed its execution, the saved register values, including the PC, are popped (retrieved) from the stack and reloaded into their respective registers. This restores the CPU to its exact pre-interrupt state so the suspended process can resume.
PastPaper.markingScheme
Award marks as follows: - 1 mark: Stating that the current register values and PC are pushed / saved onto a stack. - 1 mark: Stating that these values are popped / retrieved from the stack and loaded back into the registers once the ISR finishes. - 0.5 marks: Explaining that this preservation allows the CPU to resume the original program from the exact point where it was interrupted. (Maximum 2.5 marks)
PastPaper.question 12 · Short Answer
2.5 PastPaper.marks
State the main purpose of an assembler. Explain why an assembler is described as a 'one-to-one' translator, making reference to assembly language instructions and machine code.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Purpose: An assembler translates source code written in assembly language (a low-level programming language using mnemonics) into machine code (binary instructions) so that the computer's CPU can execute it. 2. One-to-one: Unlike high-level language compilers or interpreters where a single statement can translate into many machine instructions, each assembly language instruction translates directly into one equivalent machine code instruction.
PastPaper.markingScheme
Award marks as follows: - 1 mark: Identifying the purpose of an assembler as translating assembly language (source code) into machine code (object code). - 1 mark: Explaining the 'one-to-one' translation mapping (each assembly mnemonic/instruction translates to exactly one machine code instruction). - 0.5 marks: Contrasting this with high-level languages (where a one-to-many relationship exists) or highlighting its low-level nature. (Maximum 2.5 marks)
PastPaper.question 13 · short-answer
1.5 PastPaper.marks
An 8-bit register contains the two's complement binary representation of \(-24\). Show the representation of this number in the register, and then perform an arithmetic shift right by 2 places. Give the final 8-bit binary representation.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
First, represent \(-24\) in 8-bit two's complement. Since \(+24\) is 00011000, the two's complement representation of \(-24\) is 11101000. Next, perform an arithmetic shift right (ASR) of 2 places. An ASR shifts all bits to the right while preserving the sign bit (the MSB remains 1). Shift 1: 11110100. Shift 2: 11111010. This represents \(-6\), which is the correct mathematical result of \(-24 / 4 = -6\).
PastPaper.markingScheme
0.5 marks: Correctly identifying the starting two's complement representation of \(-24\) as 11101000. 1.0 mark: Correctly performing the arithmetic shift right by 2 places, preserving the sign bit, resulting in 11111010.
PastPaper.question 14 · short-answer
1.5 PastPaper.marks
Add the following two 8-bit unsigned binary integers: `10110110` and `01101001`. State the 8-bit sum and whether an overflow error has occurred, justifying your answer.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Perform binary addition: 10110110 (182 in denary) + 01101001 (105 in denary). Calculating the sum: 10110110 + 01101001 = 100011111. Since the result requires 9 bits and must be stored in an 8-bit register, the 9th bit (the carry-out of the MSB) is lost, leaving the 8-bit result as 00011111. An overflow error has occurred because the correct sum (287) exceeds the maximum possible value for an 8-bit unsigned integer (255).
PastPaper.markingScheme
0.5 marks: Correct 8-bit binary sum 00011111. 1.0 mark: Correctly identifying that an overflow has occurred because the sum (287) exceeds the 8-bit maximum limit of 255 (or because a carry-out bit of 1 was generated from the MSB).
PastPaper.question 15 · short-answer
1.5 PastPaper.marks
An 8-bit register contains the unsigned binary integer `00110101`. Perform a logical shift left by 3 places. State the resulting 8-bit binary pattern and explain the mathematical effect of this operation, identifying if any precision has been lost.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The initial binary number is 00110101 (53 in denary). A logical shift left by 3 places shifts all bits 3 positions to the left, filling the right-hand empty spaces with zeros. This yields 10101000 (168 in denary). Mathematically, shifting left by 3 is equivalent to multiplying by \(2^3 = 8\). Since \(53 \times 8 = 424\), which exceeds the maximum unsigned 8-bit capacity of 255, overflow has occurred. The most significant bits (containing a '1') were discarded, meaning precision has been lost.
PastPaper.markingScheme
0.5 marks: Correct 8-bit binary pattern of 10101000. 1.0 mark: Correct explanation of the mathematical effect (multiplication by 8) and stating that precision is lost because the true value (424) exceeds the maximum 8-bit limit of 255 (overflow).
PastPaper.question 16 · short-answer
1.5 PastPaper.marks
Subtract the 8-bit two's complement binary integer `00011100` (28) from `00101010` (42) by converting the subtrahend to its negative form and adding them. Show your working and give the final 8-bit binary result.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
First, find the two's complement representation of \(-28\). The binary for \(+28\) is 00011100. Invert the bits to get 11100011, then add 1 to get 11100100. Next, perform binary addition: 00101010 (42) + 11100100 (-28). Adding these: 00101010 + 11100100 = (1)00001110. The carry-out of the MSB is discarded in two's complement addition, resulting in the final 8-bit answer of 00001110 (which is 14 in denary).
PastPaper.markingScheme
0.5 marks: Correct conversion of 00011100 to its two's complement representation 11100100. 1.0 mark: Correct addition working leading to the final 8-bit answer 00001110.
PastPaper.question 17 · short-answer
1.5 PastPaper.marks
An 8-bit register contains the two's complement representation of the number \(76\). Write the binary representation of this number, and then perform an arithmetic shift right by 3 places. State the final 8-bit binary value and its denary equivalent.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
First, represent \(76\) in 8-bit binary: 01001100. Next, perform an arithmetic shift right (ASR) by 3 places. ASR shifts all bits to the right while preserving the sign bit (the MSB remains 0). Shift 1: 00100110 (38). Shift 2: 00010011 (19). Shift 3: 00001001. The denary equivalent of 00001001 is \(8 + 1 = 9\). Note that \(76 / 2^3 = 9.5\), which rounds down to 9 in integer division.
PastPaper.markingScheme
0.5 marks: Correct 8-bit representation of 76 as 01001100. 1.0 mark: Correct shift result 00001001 with its corresponding denary value of 9.
PastPaper.question 18 · short-answer
1.5 PastPaper.marks
A logical shift right of 2 places is performed on the 8-bit unsigned binary integer `11001011`. Write down the resulting 8-bit binary pattern, and identify what information or fraction is lost due to this operation.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The initial binary number is 11001011 (203 in denary). A logical shift right by 2 places shifts all bits 2 positions to the right, inserting zeros on the left. This results in 00110010 (50 in denary). The two bits shifted out on the right are `11` (which represent the fractional values \(2^{-1} + 2^{-2} = 0.5 + 0.25 = 0.75\)). Therefore, the fractional part 0.75 (or remainder 3) is lost.
PastPaper.markingScheme
0.5 marks: Correct binary pattern 00110010. 1.0 mark: Correctly identifying that the fractional value of 0.75 (or remainder of 3 / the least significant bits '11') is lost during the operation.
PastPaper.question 19 · short_answer
2 PastPaper.marks
A logic circuit has three inputs: \(A\), \(B\), and \(C\). The output \(X\) is 1 if and only if both \(A\) and \(B\) are 1, or \(B\) is 0 and \(C\) is 1. Write the Boolean expression that represents this logic circuit.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The scenario describes two conditions under which the output \(X\) is 1. The first condition is 'both \(A\) and \(B\) are 1', which translates to the Boolean term: \(A \cdot B\). The second condition is '\(B\) is 0 and \(C\) is 1', which translates to: \(\overline{B} \cdot C\). Since the output is 1 if either of these conditions is met, the two terms are combined using the OR operator. Therefore, the complete Boolean expression is: \(X = (A \cdot B) + (\overline{B} \cdot C)\) or \(X = (A \text{ AND } B) \text{ OR } (\text{NOT } B \text{ AND } C)\).
PastPaper.markingScheme
1 mark for: \(A \cdot B\) (or \(A \text{ AND } B\)). 1 mark for: \(\overline{B} \cdot C\) (or \(\text{NOT } B \text{ AND } C\)) combined with OR. Accept equivalent Boolean algebra notations.
PastPaper.question 20 · short_answer
2 PastPaper.marks
A safety monitoring system outputs an alarm signal \(A\) (value 1) if a temperature sensor \(T\) exceeds limits (value 1) and a pressure sensor \(P\) is also high (value 1). The alarm signal \(A\) is also activated if a manual override switch \(M\) is turned on (value 1). Write the Boolean expression for the output \(A\).
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The alarm signal \(A\) is 1 if 'temperature sensor \(T\) exceeds limits AND pressure sensor \(P\) is high', represented as \(T \cdot P\). Alternatively, the alarm is activated if 'manual override switch \(M\) is turned on', represented as \(M\). Combining these with an OR gate gives the final Boolean expression: \(A = (T \cdot P) + M\) or \(A = (T \text{ AND } P) \text{ OR } M\).
PastPaper.markingScheme
1 mark for: \(T \cdot P\) (or \(T \text{ AND } P\)). 1 mark for: ORing with \(M\). Accept equivalent Boolean algebra notations.
PastPaper.question 21 · SQL Scripting
4.5 PastPaper.marks
A database contains two tables: `tblStudent` and `tblTutor`. The database schema is as follows:
Write an SQL query to retrieve the `FirstName` and `LastName` of all students, along with the `RoomNumber` of their tutor. Only display students whose tutor's `RoomNumber` starts with the letter 'B'. The results must be sorted alphabetically by `LastName`.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To query records across related tables, an INNER JOIN is used to match `TutorID` in both `tblStudent` and `tblTutor`. The `WHERE` clause filters rows where the `RoomNumber` begins with 'B' using the `LIKE` operator with the `'B%'` wildcard pattern. Finally, `ORDER BY` sorts the matching students alphabetically by their `LastName`.
PastPaper.markingScheme
1.0 Mark: SELECT clause with correct fields (FirstName, LastName, RoomNumber). 1.0 Mark: Correct INNER JOIN syntax linking tblStudent and tblTutor on TutorID. 1.0 Mark: WHERE clause with correct wildcard pattern matching (RoomNumber LIKE 'B%'). 1.0 Mark: Correct ORDER BY clause (LastName ASC or simply LastName). 0.5 Mark: Correct SQL syntax overall (e.g., proper commas, table name references).
PastPaper.question 22 · SQL Scripting
4.5 PastPaper.marks
A library database requires a new table named `BookLoan` to track when books are checked out by members. The database already contains two parent tables: - `Book` with primary key `BookID` (6-character text code) - `Member` with primary key `MemberID` (Integer)
The fields required for the new table `BookLoan` are: - `LoanID` (Integer, Primary Key) - `BookID` (Foreign Key referencing `Book(BookID)`) - `MemberID` (Foreign Key referencing `Member(MemberID)`) - `LoanDate` (Date) - `ReturnDate` (Date)
Write an SQL DDL script to create the `BookLoan` table, ensuring all specified primary and foreign key constraints are correctly defined.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The SQL table is defined using `CREATE TABLE BookLoan`. Individual fields are assigned matching data types: `INTEGER` for LoanID and MemberID, `CHAR(6)` (or `VARCHAR(6)`) for BookID, and `DATE` for LoanDate and ReturnDate. Constraints are specified by declaring `PRIMARY KEY (LoanID)` and adding separate `FOREIGN KEY` constraints referencing the respective parent tables.
PastPaper.markingScheme
1.0 Mark: Correct CREATE TABLE BookLoan block, using appropriate types (INTEGER/INT, CHAR(6)/VARCHAR(6), and DATE). 1.0 Mark: Correct identification and syntax for defining LoanID as the PRIMARY KEY. 1.5 Marks: Both FOREIGN KEY constraints correctly declared (0.75 marks each) referencing the correct target tables/attributes. 1.0 Mark: General syntax accuracy (matching brackets, fields separated by commas, correct table naming).
PastPaper.question 23 · Detailed Process Description
4 PastPaper.marks
Describe the detailed physical process of how data stored on an optical disc, such as a CD-ROM, is read by an optical drive.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. The optical disc is rotated at a constant speed by a drive motor inside the optical drive. 2. A laser diode directs a low-power laser beam through a focusing lens onto the spiral track on the underside of the disc. 3. The disc's reflective aluminum layer contains micro-features: flat regions called 'lands' and microscopic bumps/depressions called 'pits'. 4. When the laser hits a land, it reflects directly back to an optical photodetector. When it hits a pit (or the transition boundary between a pit and land), the light is scattered. 5. The photodetector measures these changes in the intensity of the reflected light, translating the transitions and flat surfaces into electrical signals that represent binary 1s and 0s.
PastPaper.markingScheme
Award 1 mark for each point up to a maximum of 4: - Mentioning that the disc is rotated by a motor and a laser beam is shone onto the surface; - Describing that the surface of the disc contains lands and pits (representing data); - Explaining that lands reflect light directly back to a photodetector while pits scatter the light; - Describing that an optical sensor/photodetector measures the intensity of the reflected light; - Explaining that the variations in reflectivity are converted into electrical/binary signals (1s and 0s).
PastPaper.question 24 · Detailed Process Description
4 PastPaper.marks
A user enters a URL into their web browser. Assuming the IP address of this URL is not currently cached anywhere, describe the process of Domain Name Service (DNS) resolution used to find the IP address.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. The client computer sends a query containing the domain name to its local DNS resolver (typically run by the ISP). 2. Since the IP is not cached, the local DNS resolver queries a Root Name Server, which directs it to the appropriate Top-Level Domain (TLD) server (such as .com or .org) based on the URL extension. 3. The local DNS resolver then queries this TLD server, which responds with the IP address of the Authoritative Name Server for that specific domain name. 4. The local DNS resolver queries this Authoritative Name Server, which returns the final IP address. 5. The resolver passes this IP address back to the web browser and caches it for future use.
PastPaper.markingScheme
Award 1 mark for each point up to a maximum of 4: - The client sends a query containing the URL to the local DNS resolver; - The resolver queries a Root Name Server (which directs it to the TLD server); - The resolver queries the TLD server (which responds with the Authoritative Name Server IP); - The resolver queries the Authoritative Name Server to get the final IP address; - The resolver returns the resolved IP address to the client browser (and caches it).
PastPaper.question 25 · Detailed Process Description
4 PastPaper.marks
Describe the step-by-step process of how an analogue sound wave is captured and converted into digital data so it can be stored on a computer.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Physical sound waves are captured by a microphone (transducer), which converts them into a continuous analogue electrical voltage signal. 2. This analogue signal is input into an Analogue-to-Digital Converter (ADC). 3. The ADC measures (samples) the amplitude of the analogue electrical signal at regular, predefined time intervals. The frequency of these measurements is the sampling rate. 4. The amplitude of each sample is quantized, which means it is rounded to the nearest discrete value on a scale defined by the sampling resolution (bit depth). 5. These discrete values are converted into binary numbers and stored sequentially in the audio file.
PastPaper.markingScheme
Award 1 mark for each point up to a maximum of 4: - Sound wave is captured by a microphone and converted into an analogue electrical signal; - Analogue signal is measured/sampled at regular time intervals (sampling rate); - The amplitude of each sample is measured; - These measured amplitudes are quantized (rounded to the nearest discrete level); - The discrete values are encoded into binary numbers based on the sampling resolution/bit depth.
PastPaper.question 26 · Detailed Process Description
4 PastPaper.marks
Explain the process of how a digital signature is generated by a sender and subsequently verified by a recipient to guarantee both the authenticity and integrity of a sent document.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Creation: The sender runs the document content through a cryptographic hash function to produce a unique, fixed-size message digest. 2. The sender encrypts this message digest using their own private key to generate the digital signature, which is then attached to the document. 3. Verification: The recipient receives the document and the digital signature, and decrypts the signature using the sender's public key to recover the original message digest. 4. The recipient applies the exact same cryptographic hash function to the received document to generate a new message digest. 5. The recipient compares the recovered message digest with the newly generated message digest. If they match, authenticity (proving who sent it) and integrity (proving it was not altered) are confirmed.
PastPaper.markingScheme
Award 1 mark for each point up to a maximum of 4: - Sender hashes the original document to produce a message digest; - Sender encrypts this digest using their own private key to create the digital signature; - Recipient decrypts the digital signature using the sender's public key to obtain the original digest; - Recipient hashes the received document using the same hash algorithm to generate a new digest; - Recipient compares the two digests: a match confirms both integrity and authenticity.
Paper 2 Fundamental Problem-solving and Programming Skills
Answer all questions on the question paper. Use of standard pseudocode notations only.
12 PastPaper.question · 69 PastPaper.marks
PastPaper.question 1 · Expression Evaluation
2 PastPaper.marks
Evaluate the following pseudocode expression. Show your working. DECLARE Word : STRING; DECLARE Code : STRING; Word <- 'COMPUTING'; Code <- '9618'; MID(Word, (LENGTH(Code) MOD 3) + 2, 4) & RIGHT(Code, 2)
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Step 1: Evaluate LENGTH(Code) which is LENGTH('9618') = 4. Step 2: Evaluate 4 MOD 3 = 1. Step 3: Add 2 to the result: 1 + 2 = 3. Step 4: Evaluate MID(Word, 3, 4) which extracts 4 characters from 'COMPUTING' starting at index 3: 'MPUT'. Step 5: Evaluate RIGHT(Code, 2) which extracts the 2 rightmost characters from '9618': '18'. Step 6: Concatenate the two parts: 'MPUT' & '18' = 'MPUT18'.
PastPaper.markingScheme
1 mark for evaluating the index and extracting 'MPUT' correctly. 1 mark for the correct final answer 'MPUT18' (accept with or without quotation marks).
PastPaper.question 2 · Expression Evaluation
2 PastPaper.marks
Evaluate the following pseudocode expression. Show your working. DECLARE X : REAL; DECLARE Y : INTEGER; X <- 14.7; Y <- 3; INT(X) DIV Y + (12 MOD (Y + 2))
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Step 1: Evaluate INT(X) which is INT(14.7) = 14. Step 2: Evaluate 14 DIV Y which is 14 DIV 3 = 4 (integer division). Step 3: Evaluate the parenthesized term (Y + 2) which is 3 + 2 = 5. Step 4: Evaluate 12 MOD 5 = 2. Step 5: Add the two terms: 4 + 2 = 6.
PastPaper.markingScheme
1 mark for correct evaluation of the left-hand term INT(X) DIV Y as 4. 1 mark for correct final answer 6.
PastPaper.question 3 · Expression Evaluation
2 PastPaper.marks
Evaluate the following pseudocode expression. Show your working. DECLARE Word1 : STRING; DECLARE Word2 : STRING; Word1 <- 'TRACK'; Word2 <- 'TRACE'; (LEFT(Word1, 3) = LEFT(Word2, 3)) AND (RIGHT(Word1, 2) > RIGHT(Word2, 2))
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Step 1: Evaluate LEFT(Word1, 3) which is LEFT('TRACK', 3) = 'TRA'. Step 2: Evaluate LEFT(Word2, 3) which is LEFT('TRACE', 3) = 'TRA'. Step 3: Compare 'TRA' = 'TRA' which is TRUE. Step 4: Evaluate RIGHT(Word1, 2) which is RIGHT('TRACK', 2) = 'CK'. Step 5: Evaluate RIGHT(Word2, 2) which is RIGHT('TRACE', 2) = 'CE'. Step 6: Compare 'CK' > 'CE'. Since 'K' is alphabetically greater than 'E', 'CK' > 'CE' evaluates to TRUE. Step 7: Evaluate TRUE AND TRUE which is TRUE.
PastPaper.markingScheme
1 mark for evaluating both string comparisons correctly: ('TRA' = 'TRA' is TRUE) and ('CK' > 'CE' is TRUE). 1 mark for the correct final logical value TRUE (accept True).
PastPaper.question 4 · free_text
3 PastPaper.marks
A modular program is designed with a parent module CalculateTax that calls a child module GetTaxRate. The modules pass the following parameters: - CalculateTax passes IncomeCode (a string value) to GetTaxRate. - GetTaxRate returns the corresponding numeric TaxRate and a boolean flag CodeValid back to CalculateTax.
Describe how these three parameters are represented on the connection line of a structure chart. For each parameter, your description must include: 1. The direction of the parameter arrow. 2. The type of circle on the end of the arrow (open/empty vs. filled/solid). 3. The parameter name associated with the arrow.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
In a structure chart, parameters are shown as arrows running parallel to the line connecting the calling module and the called module. - IncomeCode is a data parameter (data couple) passed from parent to child: Arrow points down, with an open circle. - TaxRate is a data parameter (data couple) returned from child to parent: Arrow points up, with an open circle. - CodeValid is a control parameter (control couple or flag) returned from child to parent: Arrow points up, with a filled circle.
PastPaper.markingScheme
Award 1 mark for each correct parameter description: - IncomeCode: Arrow pointing downwards (from CalculateTax to GetTaxRate) AND open/unfilled circle AND labeled IncomeCode. - TaxRate: Arrow pointing upwards (from GetTaxRate to CalculateTax) AND open/unfilled circle AND labeled TaxRate. - CodeValid: Arrow pointing upwards (from GetTaxRate to CalculateTax) AND filled/solid circle AND labeled CodeValid.
PastPaper.question 5 · free_text
3 PastPaper.marks
An algorithm is to be represented using a flowchart. The algorithm reads 10 numbers from the user and calculates their sum. The following logic must be represented: 1. The variables Count and Sum are both initialized to 0. 2. A post-condition loop is used. In each iteration: - A value X is input. - X is added to Sum. - Count is incremented by 1. 3. The loop terminates when Count reaches 10. This is implemented using a decision box at the end of the loop.
Describe: - (a) The exact contents of the process box(es) used for initialization. - (b) The exact contents of the process box(es) used inside the loop. - (c) The text inside the decision box at the end of the loop, and which of its exit lines (Yes or No) loops back to the input step.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To model this algorithm as a flowchart: - Initialization: A process block containing the assignments: Count ← 0 and Sum ← 0. - Loop processes: Inside the loop, after the input block for X, a process block containing the assignments: Sum ← Sum + X and Count ← Count + 1. - Loop termination: A decision diamond containing a condition such as Count = 10. If the condition is Count = 10: The 'No' (or 'False') exit line loops back to the input block, and the 'Yes' (or 'True') line exits the loop. If the condition is Count < 10: The 'Yes' (or 'True') exit line loops back to the input block, and the 'No' (or 'False') line exits the loop.
PastPaper.markingScheme
Award 1 mark for each part: - (a) Initialization process box(es) contain assignment of 0 to both Count and Sum (e.g. Count ← 0, Sum ← 0). - (b) Loop process box(es) contain the correct assignment statements: Sum ← Sum + X AND Count ← Count + 1. - (c) Correct decision box condition and loop-back line specified. Either: Condition: Count = 10 (or Count >= 10) AND the 'No' / 'False' line loops back; OR Condition: Count < 10 AND the 'Yes' / 'True' line loops back.
PastPaper.question 6 · free_text
3 PastPaper.marks
A software designer is drawing a structure chart for a program. - The parent module RunProgram calls two child modules, ProcessRefund and ProcessSale. A condition determines which one of these two modules is called. - The parent module RunProgram also calls a child module UpdateLog repeatedly in a loop.
Describe: 1. The symbol used to indicate selection (conditional calling of ProcessRefund and ProcessSale), and exactly where it is drawn. 2. The symbol used to indicate iteration (repeated calling of UpdateLog), and exactly where it is drawn. 3. The difference between a data couple and a control couple in terms of their representation on the connection lines.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
In structure charts: - Selection is indicated by a small diamond symbol placed on the bottom edge of the parent module box, right at the point where the connection lines branch off to the conditional modules. - Iteration is indicated by a curved arrow (a loop arc) drawn across or around the connection line that links the parent module to the repeated module. - Data vs. Control couple: A data couple (representing regular variables/values passed) is shown with an arrow ending in an open (empty/white) circle. A control couple (representing flags, boolean status indicators, or signals) is shown with an arrow ending in a filled (solid/black) circle.
PastPaper.markingScheme
Award 1 mark per description: - Selection symbol and position: Diamond symbol AND positioned on the bottom edge of the parent module box (RunProgram). - Iteration symbol and position: Curved loop arrow AND drawn across/around the connection line to the child module (UpdateLog). - Data vs Control representation: Data couple has an open/empty/unfilled circle AND control couple has a filled/solid/black circle.
A weather research station records daily temperatures in a 1D array, Readings, of 100 elements (indexed 1 to 100). Write a pseudocode function MaxRun(Readings : ARRAY, Threshold : REAL) RETURNS INTEGER that calculates and returns the length of the longest consecutive sequence of days where the temperature recorded is strictly greater than the given Threshold. If no temperatures exceed the threshold, the function should return 0.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
FUNCTION MaxRun(Readings : ARRAY OF REAL, Threshold : REAL) RETURNS INTEGER DECLARE MaxCount : INTEGER DECLARE CurrentCount : INTEGER DECLARE i : INTEGER
MaxCount <- 0 CurrentCount <- 0
FOR i <- 1 TO 100 IF Readings[i] > Threshold THEN CurrentCount <- CurrentCount + 1 IF CurrentCount > MaxCount THEN MaxCount <- CurrentCount ENDIF ELSE CurrentCount <- 0 ENDIF ENDFOR
RETURN MaxCount ENDFUNCTION
PastPaper.markingScheme
1 Mark: Correct FUNCTION header with parameters (Readings, Threshold) and return type INTEGER. 1 Mark: Initialization of tracking variables (MaxCount, CurrentCount) to 0. 1 Mark: Correct FOR loop from 1 to 100 to iterate through the array elements. 1.5 Marks: Correct logical check of array element against Threshold and increment of CurrentCount. 1 Mark: Correct reset of CurrentCount to 0 in the ELSE block. 1 Mark: Correct tracking of the maximum contiguous sequence and returning the final MaxCount value.
A text file, ClassData.txt, contains information about students in a class. Each line of the file is a string of format ',', where StudentID is a string starting with an alphabetic character (e.g., 'A120', 'B104') and Score is a valid integer between 0 and 100. Write a pseudocode procedure AverageMarkA() that reads all records from ClassData.txt, calculates the average mark of all students whose ID begins with the letter 'A', and outputs the result. Assume the file exists and is not empty. Use standard 9618 pseudocode built-in string functions: LEFT(Str, Length), MID(Str, Start, Length), LENGTH(Str), INSTRING(Str, Pattern), and conversion function STRING_TO_NUM(Str).
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
PROCEDURE AverageMarkA() DECLARE Line : STRING DECLARE ID : STRING DECLARE MarkStr : STRING DECLARE Mark : INTEGER DECLARE Total : INTEGER DECLARE Count : INTEGER DECLARE CommaPos : INTEGER DECLARE Average : REAL
Total <- 0 Count <- 0
OPENFILE "ClassData.txt" FOR READ WHILE NOT EOF("ClassData.txt") READFILE "ClassData.txt", Line CommaPos <- INSTRING(Line, ",") ID <- LEFT(Line, CommaPos - 1) IF LEFT(ID, 1) = "A" THEN MarkStr <- MID(Line, CommaPos + 1, LENGTH(Line) - CommaPos) Mark <- STRING_TO_NUM(MarkStr) Total <- Total + Mark Count <- Count + 1 ENDIF ENDWHILE CLOSEFILE "ClassData.txt"
IF Count > 0 THEN Average <- Total / Count OUTPUT "Average mark: ", Average ELSE OUTPUT "No matching student records found" ENDIF ENDPROCEDURE
PastPaper.markingScheme
1 Mark: Correctly open and close "ClassData.txt" file with correct modes (READ). 1 Mark: Correct loop syntax using NOT EOF("ClassData.txt"). 1.5 Marks: Locate the position of the comma and extract the ID and MarkStr substrings correctly. 1 Mark: Check if the first character of the student ID is "A". 1 Mark: Accumulate marks into Total and increment Count within the conditional block. 1 Mark: Check if Count > 0 to avoid division by zero, calculate the average, and output it.
A circular queue of capacity 10 is implemented using a 1D array Queue of size 10 (indexed 1 to 10). The queue uses three global variables: HeadPointer (points to the front item), TailPointer (points to the rear item), and NumItems (stores the total count of items in the queue). When the queue is empty, HeadPointer is 1, TailPointer is 0, and NumItems is 0. Write a pseudocode procedure Enqueue(NewItem : STRING) that adds an item to the queue. The procedure must check if the queue is full, handle pointer wrap-around correctly, and update all pointers and counts.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
PROCEDURE Enqueue(NewItem : STRING) IF NumItems = 10 THEN OUTPUT "Queue overflow error" ELSE TailPointer <- TailPointer + 1 IF TailPointer > 10 THEN TailPointer <- 1 ENDIF Queue[TailPointer] <- NewItem NumItems <- NumItems + 1 ENDIF ENDPROCEDURE
PastPaper.markingScheme
1 Mark: Check if the queue is full (NumItems = 10) and output an error message. 1.5 Marks: Correctly increment TailPointer and handle circular wrap-around (if TailPointer > 10 then TailPointer <- 1, or modulo equivalents). 1.5 Marks: Store NewItem in Queue at the correct index (TailPointer). 1.5 Marks: Correctly increment NumItems by 1. 1 Mark: Clean implementation structure with matching nested IF / ELSE statements.
Write a pseudocode function CaesarCipher(Plaintext : STRING, Shift : INTEGER) RETURNS STRING that implements a Caesar shift cipher. The function must loop through every character of Plaintext. If a character is an uppercase letter ('A' to 'Z'), shift it forward in the alphabet by the Shift amount (wrapping around to 'A' if the shift goes past 'Z'). Any non-uppercase letters or punctuation characters must remain unchanged. Assume Shift is an integer between 1 and 25. Use built-in functions ASC(Char) which returns the ASCII code of a character, and CHR(Val) which returns the character matching an ASCII code. Note: ASCII value for 'A' is 65 and 'Z' is 90.
Ciphertext <- "" FOR i <- 1 TO LENGTH(Plaintext) NextChar <- MID(Plaintext, i, 1) AscVal <- ASC(NextChar) IF AscVal >= 65 AND AscVal <= 90 THEN AscVal <- AscVal + Shift IF AscVal > 90 THEN AscVal <- AscVal - 26 ENDIF NextChar <- CHR(AscVal) ENDIF Ciphertext <- Ciphertext & NextChar ENDFOR RETURN Ciphertext ENDFUNCTION
PastPaper.markingScheme
1 Mark: Correct FUNCTION header with appropriate parameters and RETURN type STRING. 1 Mark: Loop running from 1 to the length of Plaintext. 1 Mark: Extracting individual characters correctly using MID(Plaintext, i, 1). 1.5 Marks: Logical check for uppercase characters (ASCII 65 to 90) and shifting by Shift. 1 Mark: Correct handling of the alphabet wrap-around (subtracting 26 if shifted value exceeds 90). 1 Mark: Accumulating characters to the output variable Ciphertext and returning it.
PastPaper.question 11 · practical
14 PastPaper.marks
An inventory system stores product information in a sequential text file named "Inventory.txt". For each product, four consecutive lines in the text file represent: - Product ID (String) - Product Name (String) - Quantity in Stock (Integer) - Unit Price (Real)
An array of records, "LowStockList", is used to temporarily store products with quantities below a certain threshold. The array has a maximum capacity of 100 elements.
(a) Define a record type, "ProductRecord", in pseudocode, containing the fields described above. [2 marks]
(b) Write a pseudocode procedure, "IdentifyLowStock", which: - Takes an integer parameter, "ThresholdValue", representing the minimum stock level. - Declares the array "LowStockList" of type "ProductRecord" (indexed 1 to 100). - Opens the file "Inventory.txt" for reading. - Reads each product's data from the file and checks if the Quantity in Stock is strictly less than "ThresholdValue". - If it is, and the array is not full, stores the product's details into the next available index of "LowStockList". - Closes the file "Inventory.txt" after reaching the end of the file. - Opens a new text file named "LowStockAlert.txt" for writing. - Writes all records stored in "LowStockList" to "LowStockAlert.txt", using the same four-line format as the original file. - Closes the file "LowStockAlert.txt". - Outputs a message stating the total number of low-stock products found and written.
You should assume that the file "Inventory.txt" exists and contains valid data, but it may contain more products than can fit in the array (the array must not overflow).
Use standard Cambridge International AS & A Level pseudocode. [12 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Part (a) Solution: ```pseudocode TYPE ProductRecord DECLARE ID : STRING DECLARE Name : STRING DECLARE Quantity : INTEGER DECLARE UnitPrice : REAL ENDTYPE ```
Part (a) [2 Marks]: - 1 mark: Correct syntax for TYPE definitions with TYPE and ENDTYPE keywords. - 1 mark: All 4 fields defined correctly with matching data types (ID as STRING, Name as STRING, Quantity as INTEGER, UnitPrice as REAL/NUMERIC).
Part (b) [12 Marks]: - 1 mark: Correct procedure header taking "ThresholdValue : INTEGER" as parameter. - 1 mark: Local array "LowStockList" declared with bounds [1:100] of type "ProductRecord". - 1 mark: Initializing a tracker/counter index variable (e.g., Count <- 0) before reading. - 1 mark: Opening "Inventory.txt" for READ and closing it properly at the correct location. - 1 mark: Reading four separate values consecutively for each product from the text file. - 1 mark: Looping using WHILE NOT EOF("Inventory.txt") or equivalent construct to process files. - 1 mark: Safe index condition (e.g., Count < 100) inside loop to prevent array overflow. - 1 mark: Correct comparison of read quantity with ThresholdValue. - 1 mark: Opening "LowStockAlert.txt" for WRITE and closing it properly. - 1 mark: Loop iterating correctly from 1 to Count (only processed items). - 1 mark: Writing four consecutive lines per matching product in identical layout to file. - 1 mark: Printing an informative output message featuring the final written count.
PastPaper.question 12 · practical
14 PastPaper.marks
An oceanographic research station records temperature readings from a 10 by 10 grid of sensors. The data is saved daily in a text file named "DailyReadings.txt", containing up to 100 temperature readings (as real numbers) listed line-by-line in row-major order (first 10 lines for row 1, next 10 lines for row 2, and so on).
Write a pseudocode function "LoadAndAnalyze" that performs the following tasks: 1. Declares a local 2D array "SensorData" of size 10 rows by 10 columns to store real numbers. 2. Opens the file "DailyReadings.txt" for reading. 3. Reads the values from the file into the 2D array. 4. If the file ends before all 100 array elements are filled, fills any remaining elements in the array with the error code value -99.9. 5. Closes the file "DailyReadings.txt". 6. Calculates and returns the maximum absolute temperature difference between any two horizontally adjacent valid sensors (i.e., between element [Row, Col] and element [Row, Col + 1] for all rows from 1 to 10 and columns from 1 to 9). 7. A sensor is invalid if its value is -99.9. Any difference calculation involving one or more invalid sensors must be ignored. 8. If no valid differences can be calculated (e.g., because there are not enough adjacent valid sensors), the function should return -1.0.
Use standard Cambridge International AS & A Level pseudocode. [14 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
```pseudocode FUNCTION LoadAndAnalyze() RETURNS REAL DECLARE SensorData : ARRAY[1:10, 1:10] OF REAL DECLARE Row, Col : INTEGER DECLARE TempValue : REAL DECLARE MaxDiff, CurrentDiff : REAL DECLARE ValidDiffFound : BOOLEAN
OPENFILE "DailyReadings.txt" FOR READ
FOR Row <- 1 TO 10 FOR Col <- 1 TO 10 IF NOT EOF("DailyReadings.txt") THEN READFILE "DailyReadings.txt", TempValue SensorData[Row, Col] <- TempValue ELSE SensorData[Row, Col] <- -99.9 ENDIF NEXT Col NEXT Row
CLOSEFILE "DailyReadings.txt"
MaxDiff <- -1.0 ValidDiffFound <- FALSE
FOR Row <- 1 TO 10 FOR Col <- 1 TO 9 IF SensorData[Row, Col] <> -99.9 AND SensorData[Row, Col + 1] <> -99.9 THEN CurrentDiff <- SensorData[Row, Col] - SensorData[Row, Col + 1] IF CurrentDiff < 0 THEN CurrentDiff <- CurrentDiff * -1.0 ENDIF
IF NOT ValidDiffFound OR CurrentDiff > MaxDiff THEN MaxDiff <- CurrentDiff ValidDiffFound <- TRUE ENDIF ENDIF NEXT Col NEXT Row
IF ValidDiffFound THEN RETURN MaxDiff ELSE RETURN -1.0 ENDIF ENDFUNCTION ```
PastPaper.markingScheme
- 1 mark: Correct function header and corresponding returns type REAL. - 1 mark: Declaration of local 2D Array SensorData of correct dimensions [1:10, 1:10] and type REAL. - 1 mark: Opening file "DailyReadings.txt" for reading and closing file correctly. - 2 marks: Correctly nested loops (Row and Col loops) to traverse the 2D array. - 2 marks: Correct use of EOF checking inside the input loop to fill with actual readings or default -99.9. - 1 mark: Inner loop limits for calculation correctly bound to column 1 to 9 (preventing index out of range). - 2 marks: Checking both adjacent cells in the row to ensure neither value is -99.9. - 2 marks: Computing the absolute difference correctly (handles negative bounds without built-ins, or uses ABS). - 1 mark: Logic to correctly isolate maximum difference using a boolean flag or dynamic assignment. - 1 mark: Correctly returns maximum difference or returns -1.0 when no valid calculations occurred.
Paper 3 Advanced Theory
Answer all questions. Show your working where requested to gain full marks.
15 PastPaper.question · 61.5 PastPaper.marks
PastPaper.question 1 · structural
3 PastPaper.marks
A real number is stored in a 12-bit normalized floating-point representation, with an 8-bit mantissa and a 4-bit exponent. Both the mantissa and the exponent are stored in two's complement form.
Calculate the normalized floating-point representation for the denary value \(-3.25\) in this format. Show your working.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To convert \(-3.25\) to normalized floating-point representation:
1. Express the denary number in binary fraction form: \(-3.25 = -4 + 0.75 = -4 + 0.5 + 0.25\) Alternatively, we find a mantissa \(M\) in the range \([-1, -0.5)\) such that \(M \times 2^E = -3.25\). If \(E = 2\) (exponent \(2\)), then \(M = -3.25 / 4 = -0.8125\). This fits the normalized negative mantissa range.
2. Convert the mantissa \(-0.8125\) to 8-bit two's complement: \(-0.8125 = -1 + 0.1875 = -1 + 0.125 + 0.0625\) With binary weights of \(-2^0, 2^{-1}, 2^{-2}, 2^{-3}, 2^{-4}, 2^{-5}, 2^{-6}, 2^{-7}\): The binary representation is `1.0011000` (which is `10011000` as an 8-bit string).
3. Convert the exponent \(E = 2\) to 4-bit two's complement: \(2 = 0010_2\).
PastPaper.markingScheme
1 mark for identifying the correct exponent value of \(2\) (or binary `0010`). 1 mark for calculating the correct mantissa value of \(-0.8125\) (or showing the binary shift). 1 mark for the correct final binary string (Mantissa: `10011000` and Exponent: `0010`).
PastPaper.question 2 · structural
3 PastPaper.marks
A real number is stored in a 12-bit normalized floating-point representation, with an 8-bit mantissa and a 4-bit exponent. Both the mantissa and the exponent are stored in two's complement form.
Convert the following floating-point binary number into denary. Show your working.
**Mantissa:** `10110000` **Exponent:** `0100`
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To convert the binary floating-point representation to denary:
1. Convert the 8-bit mantissa `10110000` to denary: The binary point is after the first bit: `1.0110000` Since the MSB is 1, it represents a negative value: \(\text{Value} = -1 + (0 \times 0.5) + (1 \times 0.25) + (1 \times 0.125) = -1 + 0.375 = -0.625\).
2. Convert the 4-bit exponent `0100` to denary: `0100` is a positive binary integer: \(4\).
1 mark for converting the mantissa to \(-0.625\) (or equivalent fraction \(-5/8\)). 1 mark for converting the exponent to \(4\). 1 mark for calculating the correct final denary value of \(-10\).
PastPaper.question 3 · structured
4.5 PastPaper.marks
An online retail server uses Transport Layer Security (TLS) to encrypt sensitive data during customer transactions.
(a) Explain how TLS utilizes both asymmetric and symmetric encryption to establish and maintain a secure session. [3]
(b) Explain why symmetric encryption is used for data transmission instead of relying entirely on asymmetric encryption. [1.5]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
During the TLS handshake, asymmetric encryption is utilized to authenticate the server and securely exchange session key material. The client uses the server's public key (retrieved from its digital certificate) to encrypt a pre-master secret. Only the server, using its private key, can decrypt this message. Both parties then generate a matching symmetric session key from this secret. Once the handshake is complete, symmetric encryption is used for all subsequent data transmission because it requires significantly less computational power and is much faster than asymmetric encryption, allowing real-time data transfer.
PastPaper.markingScheme
Part (a): Up to 3 marks: - 1 mark: Asymmetric encryption is used during the handshake phase to establish identity and safely share key material. - 1 mark: The client encrypts a pre-master secret / session key material using the server's public key (from the digital certificate). - 1 mark: The server decrypts this with its matching private key, ensuring only the intended server can access the key. - 1 mark: Both client and server calculate a matching symmetric session key from the shared secret.
Part (b): Up to 1.5 marks: - 1 mark: Symmetric encryption is computationally much faster and requires less CPU overhead than asymmetric encryption, making it suitable for high-volume, real-time data transmission. - 0.5 marks: Asymmetric encryption uses much larger key sizes and complex mathematical operations, which would cause unacceptable latency if used to encrypt all web traffic.
PastPaper.question 4 · structured
4.5 PastPaper.marks
An enterprise network is allocated the IPv4 address block \(192.168.12.0/22\).
(a) State the subnet mask for this block in dotted decimal notation. [1]
(b) Calculate the total number of unique IP addresses available within this \(/22\) block. [1]
(c) The network administrator wants to divide this allocated block into exactly 4 subnets of equal size. (i) State the CIDR prefix (e.g., \(/xx\)) for each new subnet. [1] (ii) Calculate the maximum number of usable host addresses in each of these subnets, showing your working. [1.5]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
For (a), a /22 subnet mask has 22 network bits (ones) and 10 host bits (zeros). The binary representation is 11111111.11111111.11111100.00000000, which equals 255.255.252.0.
For (b), with 10 host bits, the total number of unique IP addresses is \(2^{10} = 1024\).
For (c)(i), to split the block into 4 equal subnets, we need \(\log_2(4) = 2\) bits. We add these 2 bits to the network portion: \(22 + 2 = 24\), resulting in a CIDR prefix of /24.
For (c)(ii), a /24 subnet has 8 host bits, yielding \(2^8 = 256\) total addresses. Since the network address and the broadcast address are reserved, the maximum number of usable host addresses is \(256 - 2 = 254\).
PastPaper.markingScheme
(a) 1 mark for the correct dotted decimal subnet mask: 255.255.252.0. (b) 1 mark for the correct calculation of total addresses: \(2^{10} = 1024\). (c)(i) 1 mark for the correct CIDR prefix: /24. (c)(ii) 1.5 marks total: 0.5 marks for showing the subtraction of 2 reserved addresses (network and broadcast), and 1 mark for the correct final answer of 254.
PastPaper.question 5 · structured
4.5 PastPaper.marks
A secure web browser checks a website's digital certificate to authenticate the identity of the web server before establishing an HTTPS session.
Analyze the validation steps performed by the client's browser. Your response must detail the roles of the Certificate Authority (CA), cryptographic hashing, and public key cryptography during this verification process. [4.5]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The validation process involves the following technical steps: 1. The browser receives the web server's digital certificate, which contains the server's public key, certificate details, and a digital signature created by a trusted Certificate Authority (CA). 2. The browser locates the public key of that specific CA from its pre-installed local trust store. 3. The browser uses this CA public key to decrypt the digital signature on the certificate. Because the signature was created using the CA's private key, successful decryption guarantees the certificate was indeed signed by that CA (proving authenticity). 4. Decrypting the signature yields the original cryptographic hash of the certificate's contents. 5. The browser independently computes a new hash of the certificate's details using the same hashing algorithm (e.g., SHA-256). 6. The browser compares its computed hash with the decrypted hash. If they are identical, it proves the certificate has not been altered or tampered with (integrity).
PastPaper.markingScheme
Marking criteria (Max 4.5 marks): - 1 mark: Explains that the browser retrieves the server's digital certificate containing the signature and the CA's identity. - 1 mark: Explains that the browser decrypts the digital signature using the CA's public key (stored locally in the browser/OS). - 1 mark: Identifies that this decryption proves authenticity because only the CA's private key could have encrypted/signed it. - 1 mark: Explains that the browser hashes the certificate details itself and compares this hash against the decrypted hash to verify integrity (no tampering). - 0.5 marks: Explicitly notes that a mismatch in the hashes or certificate expiration results in the browser rejecting the connection as untrusted.
PastPaper.question 6 · structured
4.5 PastPaper.marks
The BitTorrent protocol is widely used for distributing large files over peer-to-peer (P2P) networks.
Describe the role of each of the following components in a BitTorrent file transfer, and analyze how the protocol achieves efficient transfer and data integrity:
(a) Tracker [1.5]
(b) Torrent file [1.5]
(c) Segment hashing and piece verification [1.5]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) The tracker acts as a central coordinator. It does not store or transfer the file itself; instead, it maintains a dynamic list of active peers (seeders and leechers) currently sharing or downloading the file, enabling them to connect directly with one another.
(b) The torrent file contains critical metadata including the URL of the tracker, file names, size, and a list of cryptographic hash values for every individual piece (segment) of the target file.
(c) The target file is split into hundreds of small, equal-sized pieces. As a peer downloads pieces in a non-sequential order from multiple sources, it immediately hashes each completed piece and compares the result against the corresponding hash in the torrent file. If the hashes match, the piece is verified; if they do not, the corrupted piece is discarded and requested again, ensuring total data integrity.
PastPaper.markingScheme
Part (a) Tracker: 1.5 marks: - 1 mark: Explains that the tracker acts as a central coordinator maintaining active IP addresses of peers (seeders/leechers). - 0.5 marks: Clarifies that the tracker does not store or transmit the payload data itself.
Part (b) Torrent file: 1.5 marks: - 1 mark: Identifies that it contains critical metadata about the download (tracker URL, file names, sizes, hash list). - 0.5 marks: Explains that this file must be obtained first by the client to initialize the transfer.
Part (c) Segment hashing and piece verification: 1.5 marks: - 1 mark: Explains that files are split into pieces and downloaded concurrently from multiple peers, and each piece's SHA-1/cryptographic hash is checked against the list in the torrent file. - 0.5 marks: Explains that this protects against malicious or corrupt data by discarding invalid pieces immediately.
PastPaper.question 7 · structured
4 PastPaper.marks
A software developer defines syntax rules using the following Backus-Naur Form (BNF) specification:
Determine whether each of the following statements is valid or invalid under these rules. If a statement is invalid, explain why.
1) u=8 2) v=uv 3) uv8=u 4) u=89
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1) Valid: The left-hand side 'u' is a valid (since can be a single ). The right-hand side '8' is a valid (since can be a single ). 2) Valid: The left-hand side 'v' is a valid . The right-hand side 'uv' is a valid (via recursive rule , where 'u' is and 'v' is ), which makes it a valid . 3) Invalid: The left-hand side is 'uv8'. According to the rules, an can only contain the letters 'u' and 'v'. It cannot contain the digit '8'. 4) Invalid: The right-hand side is '89'. A can be a (which is a single character '8' or '9') or an , but there is no rule allowing multiple digits to form a number.
PastPaper.markingScheme
1 mark: Correctly identifies statement 1 as Valid. 1 mark: Correctly identifies statement 2 as Valid. 1 mark: Correctly identifies statement 3 as Invalid and explains that cannot contain digits / '8'. 1 mark: Correctly identifies statement 4 as Invalid and explains that '89' is not a single digit / multiple digits are not allowed.
PastPaper.question 8 · structured
4 PastPaper.marks
A syntax diagram for a signed integer is defined as follows: - An optional sign (either '+' or '-') - Followed by one or more digits.
Write the BNF rules to define the non-terminal . You must also define any intermediate non-terminals you create.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To represent the syntax diagram in BNF: 1. We define the optional sign: ::= "+" | "-"
2. We define one or more digits recursively: ::= |
3. We define the final signed integer to allow either just the digits (no sign) or the sign followed by the digits: ::= |
PastPaper.markingScheme
1 mark: Correct definition of the non-terminal (accept alternative names like ). 2 marks: Correct recursive definition of one or more digits (1 mark for the base case , 1 mark for the recursive case ). 1 mark: Correct definition of combining the optional sign with the digits.
PastPaper.question 9 · structured
4 PastPaper.marks
A simple style declaration syntax is defined by the following incomplete BNF specification:
(a) - [Missing Part A] defines a value as either a word or a number: ::= | - [Missing Part B] defines a style as a property, followed by a colon, a value, and a semicolon:
PastPaper.markingScheme
1 mark: Correct BNF rule for (Missing Part A). 1 mark: Correct BNF rule for
Simplify this Karnaugh Map to write the simplified sum-of-products Boolean expression. Show your working by identifying the terms of the groups.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To simplify the Karnaugh Map, we look for the largest possible groups of 1s (groups of 1, 2, 4, 8, etc.):
1. **The Four Corners Group**: The cells at the corners contain 1s. These are cell (00,00), (00,10), (10,00), and (10,10). Grouping these four corners eliminates variables \(A\) and \(C\) because they change states. The variables that remain constant and are 0 are \(B\) and \(D\). This gives the simplified term: \(\bar{B}\bar{D}\)
2. **The Central Group**: There is a \(2 \times 2\) block in the middle containing 1s at rows 01 and 11, columns 01 and 11. Grouping these four cells eliminates variables \(A\) and \(C\). The variables that remain constant and are 1 are \(B\) and \(D\). This gives the simplified term: \(BD\)
Combining these two terms gives the final simplified sum-of-products expression: \(\bar{B}\bar{D} + BD\) (or \(BD + \bar{B}\bar{D}\))
PastPaper.markingScheme
- 1 mark for identifying the four corners group as \(\bar{B}\bar{D}\) (or showing equivalent correct grouping on the map). - 1 mark for identifying the central group as \(BD\) and writing the final correct combined expression: \(\bar{B}\bar{D} + BD\) (allow any order of terms).
Simplify this Karnaugh Map to write the simplified sum-of-products Boolean expression. Show your working by identifying the terms of the groups.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To simplify the Karnaugh Map, we identify the largest possible groups of 1s:
1. **Horizontal Group of 4**: Row 01 is completely filled with 1s. For this row, \(P = 0\) and \(Q = 1\). Since \(R\) and \(S\) vary across all columns, they are eliminated. This group yields the term: \(\bar{P}Q\)
2. **Block Group of 4**: There is a \(2 \times 2\) block of 1s spanning rows 01 and 11, and columns 00 and 01. - For rows 01 and 11, \(Q\) remains constant at 1, while \(P\) changes (eliminating \(P\)). - For columns 00 and 01, \(R\) remains constant at 0, while \(S\) changes (eliminating \(S\)). This group yields the term: \(Q\bar{R}\)
All 1s are now covered by these two groups of 4. Combining them gives the final expression: \(\bar{P}Q + Q\bar{R}\) (or \(Q\bar{R} + \bar{P}Q\))
PastPaper.markingScheme
- 1 mark for identifying the horizontal group as \(\bar{P}Q\). - 1 mark for identifying the \(2 \times 2\) block group as \(Q\bar{R}\) and writing the final correct combined expression: \(\bar{P}Q + Q\bar{R}\) (allow any order of terms).
Simplify this Karnaugh Map to write the simplified sum-of-products Boolean expression. Show your working by identifying the terms of the groups.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To simplify the Karnaugh Map, we look for the largest possible groups of 1s:
1. **Horizontal Group of 4**: Row 01 is completely filled with 1s. For this row, \(W = 0\) and \(X = 1\). All column variables are eliminated. This group yields the term: \(\bar{W}X\)
2. **Edge Wrap-around Group of 4**: The columns 00 and 10 have 1s in rows 00 and 01. Because the columns wrap around from left to right, we can group these four cells: (00,00), (00,10), (01,00), and (01,10). - For rows 00 and 01, \(W\) remains constant at 0, while \(X\) changes (eliminating \(X\)). - For columns 00 and 10, \(Z\) remains constant at 0, while \(Y\) changes (eliminating \(Y\)). This group yields the term: \(\bar{W}\bar{Z}\)
Combining these two terms gives the final simplified expression: \(\bar{W}X + \bar{W}\bar{Z}\) (or \(\bar{W}\bar{Z} + \bar{W}X\))
PastPaper.markingScheme
- 1 mark for identifying the wrap-around group of 4 as \(\bar{W}\bar{Z}\). - 1 mark for identifying the horizontal group as \(\bar{W}X\) and writing the final correct combined expression: \(\bar{W}X + \bar{W}\bar{Z}\) (allow any order of terms).
A linked list is implemented using a 1D array of records of type `Node`.
```pseudocode TYPE Node DECLARE Data : STRING DECLARE Pointer : INTEGER ENDTYPE ```
The following global variables are defined: * `List : ARRAY[0:99] OF Node` * `StartPointer : INTEGER` (initialized to -1) * `FreePointer : INTEGER` (points to the first available node in the free list)
Write pseudocode for the procedure `InsertNode(NewItem : STRING)` to insert `NewItem` in alphabetical ascending order into the list. You may assume that the list is never full (i.e. `FreePointer` is not -1).
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To insert a node into an ordered linked list: 1. Allocate a node from the free list: - `NewNodeIndex <- FreePointer` - `FreePointer <- List[FreePointer].Pointer` 2. Set the data of the new node to `NewItem` and temporarily set its pointer to `-1`: - `List[NewNodeIndex].Data <- NewItem` - `List[NewNodeIndex].Pointer <- -1` 3. Check if the list is empty (`StartPointer = -1`). If so, insert at the beginning: - `StartPointer <- NewNodeIndex` 4. If the list is not empty, traverse it using `CurrentPointer` and `PreviousPointer` to find the correct alphabetical insertion position: - Keep moving while `CurrentPointer <> -1` and the node's data is lexicographically smaller than `NewItem`. 5. Perform the insertion: - If `PreviousPointer = -1`, it means the item must be inserted before the original first node. Update `StartPointer`. - Otherwise, link the previous node's pointer to the new node, and the new node's pointer to the current node.
PastPaper.markingScheme
Marking scheme (6.5 marks total): * **1.0 mark** for taking a node from the free list and updating `FreePointer` correctly. * **1.0 mark** for storing the new item in the data field of the new node and initializing its pointer to -1. * **1.5 marks** for correctly checking if the list is empty (`StartPointer = -1`) and updating `StartPointer`. * **1.5 marks** for a loop that correctly traverses the active linked list, updating both `PreviousPointer` and `CurrentPointer` until the correct position is found or the end of the list is reached. * **1.5 marks** for the insertion logic (adjusting pointers correctly depending on whether the item is inserted at the start of the list (`PreviousPointer = -1`) or inside/at the end of the list).
A circular queue is implemented using a 1D array `Queue : ARRAY[0:9] OF STRING` and the following global variables: * `HeadPointer : INTEGER` (points to the element to be removed next, initialized to -1) * `TailPointer : INTEGER` (points to the last element added, initialized to -1) * `NumItems : INTEGER` (stores the current number of elements, initialized to 0)
Write pseudocode for the function `Enqueue(NewItem : STRING) RETURNS BOOLEAN` which attempts to add `NewItem` to the queue. - If the queue is full, the function returns `FALSE`. - Otherwise, it updates the appropriate pointers and counter, adds the item to the circular queue, and returns `TRUE`.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To implement a circular queue `Enqueue` function: 1. First, check if the queue is full. Since the queue size is 10, the queue is full when `NumItems = 10`. If so, return `FALSE`. 2. Increment the `TailPointer` circularly using modulo arithmetic: `TailPointer <- (TailPointer + 1) MOD 10`. 3. Store `NewItem` at `Queue[TailPointer]`. 4. Handle the edge case for an empty queue: If this is the first item being added (`NumItems = 0`), the `HeadPointer` must be set to point to this index as well (`HeadPointer <- TailPointer`). 5. Increment `NumItems` by 1. 6. Return `TRUE` to indicate successful insertion.
PastPaper.markingScheme
Marking scheme (6.5 marks total): * **1.0 mark** for checking if the queue is full (`NumItems = 10`) and returning `FALSE`. * **1.5 marks** for updating the `TailPointer` circularly using a modulo operation: `(TailPointer + 1) MOD 10`. * **1.0 mark** for inserting the `NewItem` into the array at the calculated index: `Queue[TailPointer] <- NewItem`. * **1.0 mark** for updating the `HeadPointer` to match the `TailPointer` (or 0) if inserting into an empty queue (`NumItems = 0`). * **1.0 mark** for incrementing `NumItems` by 1. * **1.0 mark** for returning `TRUE` at the end of the procedure.
A binary search tree is stored in a 2D array `Tree : ARRAY[0:19, 0:2]` of integers: - `Tree[Index, 0]` stores the left child pointer. - `Tree[Index, 1]` stores the integer data value. - `Tree[Index, 2]` stores the right child pointer. All unused pointers are stored as `-1`.
Write pseudocode for the recursive function `SearchTree(CurrentNode : INTEGER, SearchValue : INTEGER) RETURNS BOOLEAN` that returns `TRUE` if `SearchValue` is found in the tree, and `FALSE` otherwise.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A recursive binary search tree search contains two base cases and two recursive cases: 1. **Base Case 1**: If the `CurrentNode` is `-1`, we have reached a leaf pointer without finding the value. Return `FALSE`. 2. **Base Case 2**: If the data at the current node (`Tree[CurrentNode, 1]`) is equal to the `SearchValue`, return `TRUE`. 3. **Recursive Case 1**: If `SearchValue` is less than `Tree[CurrentNode, 1]`, recurse down the left branch using the pointer stored at `Tree[CurrentNode, 0]`. 4. **Recursive Case 2**: If `SearchValue` is greater than `Tree[CurrentNode, 1]`, recurse down the right branch using the pointer stored at `Tree[CurrentNode, 2]`.
PastPaper.markingScheme
Marking scheme (6.5 marks total): * **1.5 marks** for the base case checking if the pointer is null (`CurrentNode = -1`) and returning `FALSE`. * **1.5 marks** for the base case checking if the node contains the search value (`Tree[CurrentNode, 1] = SearchValue`) and returning `TRUE`. * **1.5 marks** for the recursive step traversing the left branch (`Tree[CurrentNode, 0]`) if `SearchValue` is smaller, including returning the result of the recursive call. * **1.5 marks** for the recursive step traversing the right branch (`Tree[CurrentNode, 2]`) if `SearchValue` is larger, including returning the result of the recursive call. * **0.5 marks** for correct overall function syntax, matching parameters, and correct array indexing.
Paper 4 Practical
Develop programs in a high-level programming language (Python, Java, or VB.NET) to resolve the specified logical problems.
Write a Python function `count_high_scores(filename, threshold)` that opens a text file named `filename`, reads integer scores (one per line), and counts how many scores are strictly greater than `threshold`. The function must handle the file not found exception by returning -1.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The function uses a try-except block to handle FileNotFoundError. It opens the file in read mode, iterates over each line, converts the line to an integer, compares it against the threshold, increments the counter, and returns the result. If the file does not exist, it returns -1.
PastPaper.markingScheme
1 mark: Correctly implementing the try-except block to catch FileNotFoundError and return -1. 1 mark: Opening the file in read mode and iterating through the lines. 1 mark: Parsing each line as an integer, comparing it to the threshold, and correctly accumulating the count.
PastPaper.question 2 · practical
3 PastPaper.marks
Write a Python function `find_product(product_list, target)` that takes a 2D list `product_list` (where each row contains `[product_id, product_name, price]`) and a string `target` representing the product ID. The function should perform a linear search to find the target product ID and return the row index. If the product is not found, return -1.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The function iterates through the 2D list using an index. It checks if the first element of each sublist (at index 0) equals the target. If a match is found, it returns the current index. If the loop completes without finding the target, it returns -1.
PastPaper.markingScheme
1 mark: Iterating through the outer list using indices (e.g., using range(len(product_list))). 1 mark: Correctly accessing the 0th element of each row and comparing it with the target. 1 mark: Returning the current index upon a match, and returning -1 after the loop finishes without finding the target.
PastPaper.question 3 · practical
3 PastPaper.marks
A binary file `inventory.dat` contains pickled records of products, where each record is a dictionary with keys `'id'` and `'stock'`. Write a Python function `get_stock(filename, search_id)` that loads records from the binary file one by one (using `pickle.load`) and returns the `'stock'` value of the product with the matching `search_id`. If the end of file is reached or the product is not found, return `None`.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The solution opens the binary file in read-binary mode ('rb'). It uses a while loop to repeatedly call `pickle.load()` inside a try-except block that handles `EOFError` when the end of the file is reached. Each record is checked for the matching 'id', returning 'stock' if found, otherwise returning `None` if the file does not exist or target is not found.
PastPaper.markingScheme
1 mark: Opening the file in read-binary ('rb') mode and using a loop to load items. 1 mark: Handling EOFError with a try-except block to gracefully stop reading at the end of the file. 1 mark: Checking the 'id' key of each loaded dictionary and returning the corresponding 'stock' value.
PastPaper.question 4 · practical
3 PastPaper.marks
Write a Python function `binary_search_lower_bound(arr, target)` that performs a binary search on a sorted 1D list of integers `arr`. The function must return the index of the first element that is greater than or equal to `target`. If all elements are smaller than `target`, return the length of the list.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The solution maintains pointers `low` and `high` and updates them based on the middle value. When `arr[mid] >= target`, it updates the answer to `mid` and searches the left half (setting `high = mid - 1`) to find the first occurrence. Otherwise, it searches the right half.
PastPaper.markingScheme
1 mark: Initializing low, high, and calculating mid correctly inside a while loop (low <= high). 1 mark: Checking if the element at mid is greater than or equal to the target and updating the search space correctly. 1 mark: Tracking and returning the correct index, including handling the case where no element matches (returning len(arr)).
PastPaper.question 5 · practical
3 PastPaper.marks
Write a Python function `find_email_line(filename, search_email)` that reads a CSV file where each line is formatted as `ID,Name,Email`. The function must find the first line (1-indexed, meaning line 1 is the first data row) containing the `search_email` in the Email column. Return the line number if found, or -1 if the email is not found or the file does not exist.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The function opens the text file in read mode. It iterates through the lines, tracks the line index starting from 1, splits each line by commas, and checks if the third element (index 2) matches the search email. If a match is found, the line index is returned. If the end of the file is reached or an exception occurs, -1 is returned.
PastPaper.markingScheme
1 mark: Safely opening and reading lines from the file, handling FileNotFoundError. 1 mark: Splitting each line by comma and checking the Email column (index 2) correctly. 1 mark: Tracking line numbers starting at 1, returning the line number on match, and returning -1 if not found.
PastPaper.question 6 · practical
3 PastPaper.marks
A class `Student` has instance variables `name` (string) and `score` (integer). Write a Python function `find_lowest_scoring_student(student_list)` that takes a list of `Student` objects as input. The function must search through the list and return the name of the student with the lowest score. If the list is empty, return an empty string `""`.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The function first checks if the list is empty and returns an empty string. Otherwise, it initializes the lowest student as the first student in the list. It iterates through the list, compares each student's score with the currently tracked minimum score, and updates the tracker if a lower score is found. Finally, it returns the name of the lowest-scoring student.
PastPaper.markingScheme
1 mark: Correctly checking for empty list and returning an empty string. 1 mark: Iterating through the student list and comparing the `score` attribute of each object. 1 mark: Correctly updating and returning the `name` attribute of the student with the lowest score.
Define a class named Book in Python with the following private attributes: Title (String), Author (String), and BorrowCount (Integer). The class must include: A constructor that takes two parameters to initialize Title and Author, and initializes BorrowCount to 0. Getter methods for all three attributes named GetTitle(), GetAuthor(), and GetBorrowCount(). A method named BorrowBook() that increments BorrowCount by 1.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
class Book: def __init__(self, Title, Author): self.__Title = Title self.__Author = Author self.__BorrowCount = 0
1 Mark: Correct class header and constructor defining private attributes (with double underscore prefix) where BorrowCount is set to 0. 1 Mark: Implementation of three getter methods with correct return statements. 1.5 Marks: Implementation of BorrowBook() to increment BorrowCount. 1 Mark: Overall syntax correctness and adhering to Python OOP standards.
Define a class named Employee in Python with the following private attributes: EmployeeID (String), BasicSalary (Float/Real), and TaxRate (Float/Real). The class must have: A constructor that takes EmployeeID and BasicSalary as parameters, and initializes TaxRate to 0.15. A method GetNetSalary() that calculates and returns the net salary using the expression: BasicSalary * (1 - TaxRate). A method SetTaxRate(NewRate) that updates TaxRate with NewRate only if NewRate is between 0.0 and 0.5 inclusive.
1 Mark: Constructor correctly setting private attributes including TaxRate to 0.15. 1.5 Marks: GetNetSalary() calculating and returning the correct mathematical expression. 1.5 Marks: SetTaxRate() validating that NewRate is within [0.0, 0.5] and updating the attribute. 0.5 Mark: Appropriate coding standards and data types utilized.
Define a class named BankAccount in Python with the following private attributes: AccountNumber (Integer), Balance (Float/Real), and Status (String). The class must have: A constructor that takes AccountNumber as a parameter, and sets Balance to 0.0 and Status to 'Active'. A getter method GetBalance() that returns the current Balance. A method Deposit(Amount) that checks if Amount is greater than 0 and Status is 'Active'. If both are true, it adds Amount to Balance and returns True; otherwise, it returns False.
Define a class named Vehicle in Python with the following private attributes: Registration (String), Mileage (Integer), and ServiceInterval (Integer). The class must include: A constructor that takes Registration and ServiceInterval as parameters, and sets Mileage to 0. A method AddMileage(Distance) that adds a positive integer Distance to Mileage (no change if negative). A method NeedsService() that returns True if Mileage is greater than or equal to ServiceInterval, and False otherwise.
Define a class named SmartLight in Python with the following private attributes: LightID (String), Brightness (Integer), and IsOn (Boolean). The class must contain: A constructor that takes LightID as a parameter, and initializes Brightness to 50 and IsOn to False. A method TogglePower() that switches the value of IsOn to its opposite boolean state. A method SetBrightness(Value) that updates Brightness to the parameter Value only if Value is between 0 and 100 inclusive.
def TogglePower(self): self.__IsOn = not self.__IsOn
def SetBrightness(self, Value): if 0 <= Value <= 100: self.__Brightness = Value
PastPaper.markingScheme
1 Mark: Constructor declaring and initializing the three private variables correctly. 1.5 Marks: TogglePower() correctly negating the current state of IsOn. 1.5 Marks: SetBrightness() correctly checking boundary bounds before modifying the private attribute. 0.5 Mark: Clean, robust, and readable OOP code structure.
Define a class named GymMember in Python with the following private attributes: MemberID (String), MembershipType (String), and Points (Integer). The class must feature: A constructor that takes MemberID and MembershipType as parameters, and sets Points to 100. A method AddPoints(Amount) that increments Points by a positive integer Amount. A method RedeemPoints(Amount) that checks if Points is greater than or equal to Amount. If so, it decrements Points by Amount and returns True; otherwise, it returns False.
Define a class named InventoryItem in Python with the following private attributes: ItemID (String), StockLevel (Integer), and ReorderLevel (Integer). The class must have: A constructor that takes ItemID and ReorderLevel as parameters, and sets StockLevel to 0. A method Restock(Quantity) that increases StockLevel by Quantity if Quantity is greater than 0. A method NeedsReorder() that returns True if StockLevel is less than or equal to ReorderLevel, and False otherwise.
1 Mark: Constructor initializing the properties and encapsulating them privately. 1.5 Marks: Restock() validating and modifying the attribute safely. 1.5 Marks: NeedsReorder() returning the logical state of comparison accurately. 0.5 Mark: Appropriate coding structure and syntax.
PastPaper.question 14 · Code Implementation
4.2 PastPaper.marks
Write a Python class definition for StackFullException (inheriting from the base Exception class), and write the push(item) method for a class Stack. The Stack class contains private attributes __elements (a list), __max_size (an integer), and __top_pointer (an integer initialized to -1). The push method must check if the stack is full before inserting, and if so, raise a StackFullException with the message 'Stack is full'. Otherwise, it must increment the pointer and add the item.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The class StackFullException is created by inheriting from the built-in Exception class. Inside the Stack class, the push method verifies if __top_pointer is greater than or equal to __max_size - 1. If this condition is met, it raises the custom exception with the required message. If not, it increments __top_pointer and stores the item at that index.
PastPaper.markingScheme
1 Mark: Declaring StackFullException inheriting from Exception. 1 Mark: Correctly checking if top pointer is at maximum index. 1 Mark: Raising StackFullException with correct error message. 1.2 Marks: Correctly incrementing top pointer and placing the item in the list.
PastPaper.question 15 · Code Implementation
4.2 PastPaper.marks
Write a Python class definition for StackEmptyException (inheriting from the base Exception class), and write the pop() method for a class Stack. The class Stack contains private attributes __elements (a list) and __top_pointer (an integer). The pop method must check if the stack is empty, and if so, raise a StackEmptyException with the message 'Stack is empty'. Otherwise, it must retrieve the element, decrement the top pointer, and return the retrieved element.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The class StackEmptyException is defined inheriting from Exception. The pop method checks if __top_pointer is equal to -1. If true, it raises the custom exception. If the stack is not empty, it stores the element at the index pointed to by __top_pointer, decrements __top_pointer by 1, and returns the stored element.
PastPaper.markingScheme
1 Mark: Declaring StackEmptyException inheriting from Exception. 1 Mark: Checking if the top pointer equals -1. 1 Mark: Raising StackEmptyException with the correct message. 1.2 Marks: Storing the top element, decrementing the top pointer, and returning the element.
PastPaper.question 16 · Code Implementation
4.2 PastPaper.marks
Write a Python code snippet that implements a test harness. It must instantiate a Stack object named my_stack with an initial maximum capacity of 5. It must then attempt to pop an element from it within a try-except block. If a StackEmptyException is raised, the program must print the message 'Error: Stack is empty'. Regardless of whether an exception is raised, the block must print 'Operation complete' in a finally section.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The test harness initializes my_stack as an instance of Stack with capacity 5. It uses a try block to call the pop method. The except block catches StackEmptyException and prints the specified error. The finally block executes print('Operation complete') to ensure the statement runs regardless of exceptions.
PastPaper.markingScheme
1 Mark: Instantiating Stack with value 5. 1.2 Marks: Attempting pop within try block. 1 Mark: Catching StackEmptyException and printing correct message. 1 Mark: Implementing a finally block that prints 'Operation complete'.
PastPaper.question 17 · Code Implementation
4.2 PastPaper.marks
Write the constructor method (__init__) for a Python class Stack that implements a bounded stack. The constructor must accept max_size as a parameter. It should validate that max_size is greater than 0, raising a ValueError with the message 'Size must be positive' if it is not. It should then initialize private attributes __max_size to the parameter, __elements to a list initialized with None of length max_size, and __top_pointer to -1.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The constructor first validates the size. If max_size is less than or equal to 0, it raises a ValueError. Otherwise, it initializes the private attributes __max_size, __elements as a list containing max_size elements of None, and __top_pointer to -1.
PastPaper.markingScheme
1 Mark: Validating max_size and raising ValueError with message. 1 Mark: Assigning __max_size. 1 Mark: Initializing __top_pointer to -1. 1.2 Marks: Creating private list __elements initialized to size max_size with None values.
PastPaper.question 18 · Code Implementation
4.2 PastPaper.marks
Write the peek() method for the Stack class in Python. This method returns the element at the top of the stack without removing it. It must check if the stack is empty and, if so, raise a StackEmptyException with the message 'Cannot peek an empty stack'. Otherwise, it returns the top element.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The peek method checks if __top_pointer is -1, which indicates that the stack has no elements. If empty, it raises StackEmptyException with the specified message. Otherwise, it retrieves and returns the element at __top_pointer without altering the pointer.
PastPaper.markingScheme
1 Mark: Correct method signature for peek. 1 Mark: Checking if top pointer is -1. 1 Mark: Raising StackEmptyException with the correct message. 1.2 Marks: Returning the correct element without modifying the top pointer.
PastPaper.question 19 · Code Implementation
4.2 PastPaper.marks
Write a Python function validate_brackets(expression) that uses a Stack instance to check if parentheses '(' and ')' in expression (a string) are balanced. Initialize a Stack of size equal to the length of the expression. Loop through each character: push '(' onto the stack, and pop from the stack when ')' is encountered. If a StackEmptyException is raised during popping, return False immediately. After checking all characters, if the stack is empty (which can be tested by calling peek() and catching StackEmptyException), return True; otherwise return False.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The function processes each character. It pushes open parentheses onto the stack and pops them for close parentheses. If it pops too many, StackEmptyException is caught and False is returned. At the end, it uses peek() inside try-except. If peek succeeds, elements remain, so it returns False. If peek raises StackEmptyException, the stack is empty and it returns True.
PastPaper.markingScheme
1 Mark: Instantiating the Stack with correct size. 1 Mark: Correctly pushing on '(' and popping on ')'. 1 Mark: Wrapping the loop in a try-except to catch StackEmptyException and returning False. 1.2 Marks: Checking if the stack is empty at the end using another try-except block on peek() and returning True/False accordingly.