An original Thinka practice paper modelled on the structure and difficulty of the Jun 2025 (V2) Cambridge International A Level Computer Science (9618) paper. Not affiliated with or reproduced from Cambridge.
Paper 12 Theory Fundamentals
Answer all questions. Calculators must not be used in this paper.
7 PastPaper.question · 75 PastPaper.marks
PastPaper.question 1 · Short Answer
8 PastPaper.marks
A sound engineer is digitising an analogue audio signal.
(a) Explain the process of sampling an analogue sound wave to convert it into a digital format. [3]
(b) Describe how increasing the sampling rate and the sampling resolution (bit depth) affects both the representation of the sound wave and the resulting file size. [3]
(c) A monophonic audio track is recorded with a sampling rate of 44,000 Hz and a sampling resolution of 16 bits. The duration of the recording is 20 seconds.
Calculate the file size of this recording in kilobytes (KB). Show your working. Assume 1 KB = 1,000 bytes. [2]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
For part (a): - The analogue sound wave is a continuous signal. - The amplitude of the wave is measured (sampled) at regular, discrete time intervals. - These continuous values are then quantized and stored as discrete binary values.
For part (b): - Increasing the sampling rate means taking more samples per second, which tracks the original analogue wave more accurately (higher fidelity) but increases the file size because more data points are recorded. - Increasing the sampling resolution means more bits are used per sample, which allows for a wider dynamic range and smaller quantization error (less distortion), but increases the file size as each individual sample requires more storage space.
Part (a) (Max 3 marks): - 1 mark: Wave amplitude is measured/sampled at regular/constant time intervals. - 1 mark: The original analogue wave is continuous. - 1 mark: Measured continuous values are converted/quantized into discrete binary values.
Part (b) (Max 3 marks): - 1 mark: Higher sampling rate provides a closer match/higher fidelity to original analogue wave but increases file size. - 1 mark: Higher sampling resolution reduces quantization error/distortion/increases dynamic range. - 1 mark: Higher sampling resolution increases file size.
Part (c) (Max 2 marks): - 1 mark: Correct working showing: \(44,000 \times 16 \times 20\) and dividing by 8. - 1 mark: Correct final calculation of 1,760 KB (accept 1760).
PastPaper.question 2 · Short Answer
8 PastPaper.marks
Data is transmitted across the internet using packet switching.
(a) Describe the structure of a standard packet of data. [3]
(b) Explain how packets are transmitted from a sender to a receiver across a packet-switched network, and how they are reassembled at the destination. [5]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
For part (a): - A data packet consists of three parts: 1. Header: Contains control information such as the source IP address, destination IP address, packet sequence number, and the protocol being used. 2. Payload: Contains the actual user data being transmitted. 3. Trailer: Contains error-detection data (e.g., checksum, cyclic redundancy check) and an end-of-packet marker.
For part (b): - The original data is split into multiple smaller packets. - Each packet is routed independently across the network. - Routers check the destination IP address in the packet header to determine the next hop/optimal path. - Packets can take different routes depending on network congestion and may arrive at the destination out of order. - Once all packets arrive, the receiver checks for transmission errors using the checksum in the trailer. - If any packet is corrupted or missing, a retransmission request is made. - The receiver uses the sequence numbers in the packet headers to reassemble the packets back into their original order.
PastPaper.markingScheme
Part (a) (Max 3 marks): - 1 mark: Header contains sender/receiver IP address, packet ID/sequence number, or protocol. - 1 mark: Payload contains the actual data being sent. - 1 mark: Trailer/footer contains error-checking data (checksum) or end-of-packet marker.
Part (b) (Max 5 marks): - 1 mark: Message is split into smaller units called packets. - 1 mark: Packets travel independently through the network. - 1 mark: Routers examine destination IP address to direct packets along the best path. - 1 mark: Packets can take different paths and can arrive out of order. - 1 mark: Receiver checks for errors using trailer/checksum (accept request for retransmission if packet is corrupt/lost). - 1 mark: Destination node uses sequence numbers in the header to reassemble packets into original order.
PastPaper.question 3 · Short Answer
8 PastPaper.marks
In assembly language, different addressing modes are used to access data.
(a) Describe the differences between the following addressing modes: (i) Immediate addressing [1] (ii) Direct addressing [1] (iii) Indirect addressing [2] (iv) Indexed addressing [2]
(b) Explain how the Program Counter (PC) and the Memory Address Register (MAR) change during the Fetch stage of the Fetch-Decode-Execute (FDE) cycle. [2]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
For part (a): - (i) Immediate addressing: The operand is the actual value to be used in the instruction (e.g., loading the constant directly). - (ii) Direct addressing: The operand is the memory address where the value is stored. - (iii) Indirect addressing: The operand is a memory address which points to another memory address that contains the actual data to be accessed. - (iv) Indexed addressing: The address of the operand is calculated by adding the value in the Index Register (IX) to the base memory address specified in the instruction.
For part (b): - During the Fetch stage, the address of the next instruction stored in the Program Counter (PC) is copied to the Memory Address Register (MAR). - The Program Counter (PC) is then incremented by 1 to point to the address of the next sequential instruction.
PastPaper.markingScheme
Part (a) (Max 6 marks): - (i) Immediate (1 mark): The operand value itself is given in the instruction. - (ii) Direct (1 mark): The address of the operand is given in the instruction. - (iii) Indirect (2 marks): The address in the instruction holds the address of the operand / pointer to the actual data. (1 mark for pointing to address, 1 mark for address holding final address). - (iv) Indexed (2 marks): The address of the operand is found by adding the value of the Index Register (IX) (1 mark) to the base address specified in the instruction (1 mark).
Part (b) (Max 2 marks): - 1 mark: The address in the PC is copied to the MAR. - 1 mark: The PC is incremented (by 1).
PastPaper.question 4 · Short Answer
8 PastPaper.marks
A training company maintains a relational database table to store records of training courses attended by employees.
- Assume an employee can attend multiple courses, and each course has a fixed title and fee. - The primary key is the composite key: `(EmployeeID, CourseCode)`.
(a) Explain why this table is in First Normal Form (1NF). [1]
(b) Identify the functional dependencies that exist in this table, and explain why the table is NOT in Second Normal Form (2NF). [3]
(c) Normalize the database design into Third Normal Form (3NF). Write down the names of the tables, their attributes, and underline the primary keys. Identify any foreign keys. [4]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
For part (a): - The table is in 1NF because there are no repeating groups of attributes, and all attribute values are atomic (each cell contains a single value).
For part (b): - The functional dependencies are: - `EmployeeID -> EmployeeName` - `CourseCode -> CourseTitle, Fee` - `(EmployeeID, CourseCode) -> DateCompleted` - The table is not in 2NF because there are partial key dependencies. Non-key attributes (`EmployeeName`, `CourseTitle`, `Fee`) are dependent on only part of the composite primary key rather than the entire primary key.
For part (c): To normalize to 3NF, we must eliminate these partial dependencies, which splits the table into three distinct tables:
Part (a) (1 mark): - 1 mark: All attributes contain atomic values / there are no repeating groups.
Part (b) (Max 3 marks): - 1 mark: Identifies partial dependencies: `EmployeeID` determines `EmployeeName` OR `CourseCode` determines `CourseTitle`/`Fee`. - 1 mark: Identifies the full key dependency: `(EmployeeID, CourseCode)` determines `DateCompleted`. - 1 mark: Explains that 2NF is violated because non-key attributes depend on only part of the composite primary key (partial key dependency exists).
Part (c) (Max 4 marks): - 1 mark: Correct `Employee` table with `EmployeeID` underlined as PK. - 1 mark: Correct `Course` table with `CourseCode` underlined as PK. - 1 mark: Correct `EmployeeCourse` table with composite key `(EmployeeID, CourseCode)` underlined as PK. - 1 mark: Explicitly identifies `EmployeeID` and `CourseCode` as foreign keys in the `EmployeeCourse` table.
PastPaper.question 5 · Short Answer
8 PastPaper.marks
An Integrated Development Environment (IDE) contains translation software and utility programs.
(a) State three differences between a compiler and an interpreter. [3]
(b) Describe the functions of the following utility software: (i) Disk defragmenter [2] (ii) File compression utility [3]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
For part (a): 1. A compiler translates the entire source code into machine code/object code at once, whereas an interpreter translates and executes the source code line-by-line. 2. A compiler generates a standalone executable file (e.g., .exe) that runs independently, whereas an interpreter must be present and run the source code every time. 3. A compiler lists all syntax errors at the end of compilation, whereas an interpreter stops execution immediately when the first error is encountered.
For part (b): (i) Disk defragmenter: - Rearranges fragmented parts of files stored on a magnetic hard drive so that all segments of individual files are stored in contiguous blocks/sectors. - This reduces the movement of the read/write heads, leading to faster file access and improved system performance.
(ii) File compression utility: - Reduces the storage size of files by applying compression algorithms (lossy or lossless). - It frees up storage space on secondary storage media. - It reduces the bandwidth required and the transfer time when transmitting files over a network or the internet.
PastPaper.markingScheme
Part (a) (Max 3 marks): - 1 mark: Compiler translates whole program at once / Interpreter translates line-by-line. - 1 mark: Compiler produces independent executable/object code / Interpreter does not produce object code. - 1 mark: Compiler reports all errors at the end / Interpreter stops execution at the first error. - 1 mark: Compiled code executes faster (after initial compile) / Interpreted code runs slower due to runtime translation.
Part (b)(i) Disk defragmenter (Max 2 marks): - 1 mark: Moves sectors/blocks of fragmented files to make them contiguous. - 1 mark: Decreases read/write head movement, which increases file access speeds.
Part (b)(ii) File compression utility (Max 3 marks): - 1 mark: Uses algorithms (lossless/lossy) to reduce overall size of a file. - 1 mark: Saves storage capacity/space on disk. - 1 mark: Enables faster file transfer/transmission times over networks/internet.
PastPaper.question 6 · Mathematical Calculations
17.5 PastPaper.marks
A specialized scientific sensor array records underwater acoustic telemetry data using a custom multi-channel audio system. The recording parameters are specified as follows: - Sampling rate: \(32,768\text{ Hz}\) - Resolution / Bit depth: \(16\text{ bits}\) - Number of channels: \(8\text{ channels}\) - Recording duration: \(128\text{ seconds}\)
Answer the following questions. Show all your working.
(a) Calculate the raw uncompressed file size of the recording in Mebibytes (MiB). Use powers of 2 in your working to demonstrate how you arrive at the final integer value. (6 marks)
(b) The resulting audio file must be transmitted from a remote buoy to a research vessel over a radio link with an effective bandwidth of \(8\text{ Mibps}\) (mebibits per second). Due to network protocol overheads (such as packet headers and error correction), there is a \(25\%\) data overhead, meaning the total transmitted data is \(1.25\) times the actual file size. Calculate the total transmission time in seconds. (5 marks)
(c) The researcher considers using compression to reduce the storage space on the buoy's local card. Explain why a lossy compression algorithm is entirely unsuitable for scientific telemetry data, and why a lossless algorithm must be used instead. (4 marks)
(d) Represent the decimal value \(-103\) as an 8-bit two's complement signed integer. Show your working. (2.5 marks)
(c) Discussion: - Lossy compression permanently deletes data (e.g., removing frequency components deemed imperceptible to human ears). - In scientific telemetry, every raw measurement represents precise environmental data. Deleting data corrupts the records and introduces artifacts, rendering the measurements scientifically invalid. - Lossless compression works by identifying and compressing redundancy without discarding any content. When decompressed, the data is bit-for-bit identical to the original, preserving the integrity of the data.
(d) Signed integer conversion: 1. Convert \(+103\) to 8-bit unsigned binary: \(103 = 64 + 32 + 4 + 2 + 1 = 01100111_2\) 2. Find the one's complement (invert all bits): \(10011000_2\) 3. Add 1 to find the two's complement: \(10011000 + 1 = 10011001_2\).
PastPaper.markingScheme
Part (a) [6 Marks]: - 1 mark: Expressing sampling rate as \(2^{15}\) (or showing equivalent calculation) - 1 mark: Expressing bit depth in bytes (2 bytes or \(2^1\)) - 1 mark: Identifying correct overall size formula (Rate * Bytes * Channels * Duration) - 1 mark: Correct calculation of total bytes as \(2^{26}\) (or \(67,108,864\) bytes) - 1 mark: Showing division by \(2^{20}\) (or \(1,048,576\)) to convert to MiB - 1 mark: Correct final answer of 64 MiB (accept 64)
Part (b) [5 Marks]: - 1 mark: Converting 64 MiB to bits/Mebibits (512 Mib) - 1 mark: Correctly applying the \(1.25\) multiplier for overhead - 1 mark: Calculating total data as 640 Mib (or \(671,088,640\) bits) - 1 mark: Showing correct division of total data by bandwidth (8 Mibps) - 1 mark: Correct final answer of 80 seconds
Part (c) [4 Marks]: - 1 mark: Stating lossy compression permanently removes data. - 1 mark: Explaining that loss of data corrupts/alters precise scientific measurements/telemetry. - 1 mark: Stating lossless compression reconstructs original data perfectly / bit-for-bit. - 1 mark: Explaining that lossless maintains scientific integrity/accuracy.
Part (d) [2.5 Marks]: - 1 mark: Correctly representing positive \(+103\) in 8-bit binary (\(01100111\)) - 1 mark: Showing correct step for two's complement (one's complement + 1 or subtracting from 256) - 0.5 marks: Correct final 8-bit binary string: \(10011001\)
PastPaper.question 7 · Boolean Proofs and Logic
17.5 PastPaper.marks
A digital safety interlock system in an industrial plant monitors two sensors: \(A\) (Over-temperature) and \(B\) (Over-pressure). The safety output warning signal, \(X\), is determined by the following Boolean expression: \(X = \overline{A \cdot B} \cdot (A + \overline{B}) \cdot (\overline{A} + B)\)
(a) Produce a complete truth table for the original unsimplified expression. Your truth table must include intermediate columns for \(\overline{A \cdot B}\), \((A + \overline{B})\), and \((\overline{A} + B)\) to show your work clearly. (6 marks)
(b) Simplify the Boolean expression for \(X\) to its simplest form containing the minimum number of literals and operators. Show every algebraic step and explicitly state the Boolean law/identity used at each step. (6.5 marks)
(c) Draw a logic circuit diagram for your simplified expression from part (b) using ONLY 2-input NOR gates. Explain your reasoning using De Morgan's Law. (5 marks)
(b) Step-by-step algebraic simplification: 1. Given: \(X = \overline{A \cdot B} \cdot (A + \overline{B}) \cdot (\overline{A} + B)\) 2. Apply De Morgan's Law to the first term: \(X = (\overline{A} + \overline{B}) \cdot (A + \overline{B}) \cdot (\overline{A} + B)\) 3. Group the first two terms and apply the Distributive Law \((Y + Z) \cdot (Y + W) = Y + (Z \cdot W)\) where \(Y = \overline{B}\), \(Z = \overline{A}\), and \(W = A\): \(X = (\overline{B} + (\overline{A} \cdot A)) \cdot (\overline{A} + B)\) 4. Apply the Complement Law \(\overline{A} \cdot A = 0\): \(X = (\overline{B} + 0) \cdot (\overline{A} + B)\) 5. Apply the Identity Law \(\overline{B} + 0 = \overline{B}\): \(X = \overline{B} \cdot (\overline{A} + B)\) 6. Apply the Distributive Law: \(X = (\overline{B} \cdot \overline{A}) + (\overline{B} \cdot B)\) 7. Apply the Complement Law \(\overline{B} \cdot B = 0\): \(X = (\overline{B} \cdot \overline{A}) + 0\) 8. Apply the Identity Law and Commutative Law: \(X = \overline{A} \cdot \overline{B}\)
(c) Circuit implementation: 1. According to De Morgan's Law: \(\overline{A} \cdot \overline{B} = \overline{A + B}\) 2. The expression \(\overline{A + B}\) is the exact logic operation performed by a standard 2-input NOR gate. 3. Therefore, the simplified expression can be fully implemented using exactly one 2-input NOR gate, with inputs \(A\) and \(B\), producing output \(X\).
PastPaper.markingScheme
Part (a) [6 Marks]: - 1 mark: Correct truth table inputs for \(A\) and \(B\) (4 standard rows). - 1 mark: Correct column for \(\overline{A \cdot B}\) (1, 1, 1, 0). - 1 mark: Correct column for \(A + \overline{B}\) (1, 0, 1, 1). - 1 mark: Correct column for \(\overline{A} + B\) (1, 1, 0, 1). - 2 marks: Correct final column \(X\) (1, 0, 0, 0) [deduct 1 mark for each incorrect row up to 2].
Part (b) [6.5 Marks]: - 1 mark: Correct application of De Morgan's Law to \(\overline{A \cdot B}\) to get \(\overline{A} + \overline{B}\). - 1.5 marks: Factoring or simplifying \((\overline{A} + \overline{B}) \cdot (A + \overline{B})\) to \(\overline{B}\) with correct justification of the Distributive and Complement laws. - 1.5 marks: Distributing \(\overline{B}\) through \((\overline{A} + B)\) to get \(\overline{B}\overline{A} + \overline{B}B\). - 1.5 marks: Eliminating \(\overline{B}B\) to 0 using Complement Law and simplifying to \(\overline{A}\overline{B}\) using Identity Law. - 1 mark: Explicitly stating the correct names of the laws used at each step (De Morgan's, Distributive, Complement, Identity).
Part (c) [5 Marks]: - 2 marks: Explaining the application of De Morgan's Law to show \(\overline{A} \cdot \overline{B} = \overline{A + B}\). - 1 mark: Stating that \(\overline{A + B}\) represents a standard NOR operation. - 2 marks: Describing or drawing the logic diagram consisting of a single NOR gate with inputs \(A\) and \(B\) yielding output \(X\).
Paper 22 Fundamental Problem-solving and Programming Skills
Answer all questions. You must refer to the accompanying pseudocode insert.
7 PastPaper.question · 75 PastPaper.marks
PastPaper.question 1 · Trace Table
10 PastPaper.marks
An algorithm is designed to perform run-length encoding on a string of uppercase characters. Below is the pseudocode of the algorithm:
- Loop Iteration 1: - i = 1 (1 <= 9 is True) - CurrentChar <- "A" - Count <- 1 - Inner loop: i+1 = 2 <= 9 AND MID("AABCCCDEE", 2, 1) = "A" is True. - Count <- 2 - i <- 2 - Inner loop: i+1 = 3 <= 9 AND MID("AABCCCDEE", 3, 1) = "B" is False. - Count > 1 (2 > 1) is True -> OutputStr <- "" + "2" + "A" = "2A" - i <- 3
- Loop Iteration 2: - i = 3 (3 <= 9 is True) - CurrentChar <- "B" - Count <- 1 - Inner loop: i+1 = 4 <= 9 AND MID("AABCCCDEE", 4, 1) = "C" is False. - Count > 1 (1 > 1) is False -> OutputStr <- "2A" + "B" = "2AB" - i <- 4
- Loop Iteration 3: - i = 4 (4 <= 9 is True) - CurrentChar <- "C" - Count <- 1 - Inner loop: i+1 = 5 <= 9 AND MID("AABCCCDEE", 5, 1) = "C" is True. - Count <- 2 - i <- 5 - Inner loop: i+1 = 6 <= 9 AND MID("AABCCCDEE", 6, 1) = "C" is True. - Count <- 3 - i <- 6 - Inner loop: i+1 = 7 <= 9 AND MID("AABCCCDEE", 7, 1) = "D" is False. - Count > 1 (3 > 1) is True -> OutputStr <- "2AB" + "3" + "C" = "2AB3C" - i <- 7
- Loop Iteration 4: - i = 7 (7 <= 9 is True) - CurrentChar <- "D" - Count <- 1 - Inner loop: i+1 = 8 <= 9 AND MID("AABCCCDEE", 8, 1) = "E" is False. - Count > 1 (1 > 1) is False -> OutputStr <- "2AB3C" + "D" = "2AB3CD" - i <- 8
- Loop Iteration 5: - i = 8 (8 <= 9 is True) - CurrentChar <- "E" - Count <- 1 - Inner loop: i+1 = 9 <= 9 AND MID("AABCCCDEE", 9, 1) = "E" is True. - Count <- 2 - i <- 9 - Inner loop: i+1 = 10 <= 9 is False. - Count > 1 (2 > 1) is True -> OutputStr <- "2AB3CD" + "2" + "E" = "2AB3CD2E" - i <- 10
- Termination: - i = 10 (10 <= 9 is False). Loop terminates. - Return "2AB3CD2E"
PastPaper.markingScheme
1 mark: Length correctly initialized to 9. 1 mark: Loop variable i initialized to 1 and increments correctly through iterations. 1 mark: Identifying CurrentChar correctly for each segment ('A', 'B', 'C', 'D', 'E'). 1 mark: Count variable correctly increments inside the loop for the 'A' segment (value 2). 1 mark: Count variable correctly increments inside the loop for the 'C' segment (value 3). 1 mark: Count variable correctly increments inside the loop for the 'E' segment (value 2). 1 mark: Correct conditional checking for Count > 1. 1 mark: OutputStr updated correctly to "2A" in iteration 1. 1 mark: OutputStr updated correctly to "2AB3C" in iteration 3. 1 mark: Final output correctly evaluated and returned as "2AB3CD2E".
PastPaper.question 2 · Trace Table
10 PastPaper.marks
A recursive function is designed to search for a local peak index in a 1D array of integers. A peak is defined as an element that is strictly greater than its immediate successor. Below is the pseudocode for the algorithm:
FUNCTION FindPeak(Arr : ARRAY[1..8] OF INTEGER, Low : INTEGER, High : INTEGER) RETURNS INTEGER DECLARE Mid : INTEGER IF Low = High THEN RETURN Low ENDIF Mid <- (Low + High) DIV 2 IF Arr[Mid] > Arr[Mid + 1] THEN RETURN FindPeak(Arr, Low, Mid) ELSE RETURN FindPeak(Arr, Mid + 1, High) ENDIF ENDFUNCTION
An array TestArr contains the following values: [2, 5, 8, 12, 10, 7, 4, 1].
Dry-run the execution of the call FindPeak(TestArr, 1, 8) by completing a trace table to track each function call, low/high bounds, mid value, condition check, and returning values.
1 mark: Correct values of Low (1) and High (8) on first call. 1 mark: Correct Mid calculation (4) on first call. 1 mark: Correct comparison evaluation (12 > 10 is True) in Call 1. 1 mark: Correct recursive parameter determination (Low=1, High=4) for second call. 1 mark: Correct Mid calculation (2) on second call. 1 mark: Correct comparison evaluation (5 > 8 is False) in Call 2. 1 mark: Correct recursive parameter determination (Low=3, High=4) for third call. 1 mark: Correct Mid calculation (3) on third call. 1 mark: Correct base case identification (Low = High = 4) on fourth call. 1 mark: Final returned value of 4 successfully propagated and stated.
PastPaper.question 3 · Trace Table
10 PastPaper.marks
A procedure is designed to analyze a 2D grid of size 3x3 and calculate the sum of horizontal and vertical neighbors for each cell. Below is the pseudocode of the algorithm:
PROCEDURE ProcessGrid(Grid : ARRAY[1..3, 1..3] OF INTEGER) DECLARE Result : ARRAY[1..3, 1..3] OF INTEGER DECLARE Row, Col : INTEGER DECLARE Neighbors : INTEGER
FOR Row <- 1 TO 3 FOR Col <- 1 TO 3 Neighbors <- 0 IF Row > 1 THEN Neighbors <- Neighbors + Grid[Row - 1, Col] ENDIF IF Row < 3 THEN Neighbors <- Neighbors + Grid[Row + 1, Col] ENDIF IF Col > 1 THEN Neighbors <- Neighbors + Grid[Row, Col - 1] ENDIF IF Col < 3 THEN Neighbors <- Neighbors + Grid[Row, Col + 1] ENDIF Result[Row, Col] <- Neighbors ENDFOR ENDFOR
FOR Row <- 1 TO 3 OUTPUT Result[Row, 1], Result[Row, 2], Result[Row, 3] ENDFOR ENDPROCEDURE
The array Grid contains the following initial state: Row 1: [1, 0, 1] Row 2: [0, 1, 0] Row 3: [1, 1, 0]
Dry-run the procedure and write the final printed grid output.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
We track the calculation of adjacent elements for each grid coordinate (Row, Col):
An array `Grades` contains 50 integer values representing exam scores of students. The indices of the array range from 1 to 50.
Write pseudocode for a procedure `ProcessGrades` that takes the `Grades` array as a parameter. The procedure must perform the following tasks: 1. Find the maximum and minimum grades in the array. 2. Calculate the average of all grades *excluding* the single maximum grade and the single minimum grade (i.e. calculate the sum of the remaining 48 grades and divide by 48). 3. Count how many grades in the entire array (including maximum and minimum) are strictly below this calculated average. 4. Output the maximum grade, the minimum grade, the calculated average, and the count of grades below the average, with appropriate descriptive messages.
You must declare all local variables used. Ensure your pseudocode follows the standard Cambridge International A Level Computer Science syllabus conventions.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
```pseudocode PROCEDURE ProcessGrades(Grades : ARRAY OF INTEGER) DECLARE MaxGrade : INTEGER DECLARE MinGrade : INTEGER DECLARE Sum : INTEGER DECLARE Average : REAL DECLARE CountBelow : INTEGER DECLARE Index : INTEGER
MaxGrade <- Grades[1] MinGrade <- Grades[1] Sum <- 0
FOR Index <- 1 TO 50 Sum <- Sum + Grades[Index] IF Grades[Index] > MaxGrade THEN MaxGrade <- Grades[Index] ENDIF IF Grades[Index] < MinGrade THEN MinGrade <- Grades[Index] ENDIF ENDFOR
Sum <- Sum - MaxGrade - MinGrade Average <- Sum / 48.0
CountBelow <- 0 FOR Index <- 1 TO 50 IF Grades[Index] < Average THEN CountBelow <- CountBelow + 1 ENDIF ENDFOR
Award marks as follows (Max 11.25 marks total): - **1 mark**: Correct procedure header taking `Grades` array as parameter and correct `ENDPROCEDURE`. - **1 mark**: Declaring all local variables with correct data types (`INTEGER`, `REAL`). - **1 mark**: Initializing `MaxGrade` and `MinGrade` to a value from the array (e.g., `Grades[1]`) and initializing `Sum` to 0. - **1 mark**: Correct loop configuration to iterate through all 50 elements of the array. - **1 mark**: Correctly finding and storing the maximum grade in the loop. - **1 mark**: Correctly finding and storing the minimum grade in the loop. - **1 mark**: Correctly summing all elements in the loop. - **1 mark**: Subtracting the maximum and minimum values from the total sum and dividing by \(48.0\) to find the average. - **1 mark**: Setting up a second loop (or alternative logical structure) to count elements below the calculated average. - **1 mark**: Correct conditional comparison (`Grades[Index] < Average`) inside the counting loop. - **1 mark**: Outputting all four requested values with descriptive strings. - **0.25 mark**: Correct indentation and clean syntax used throughout.
A software application requires user passwords to be validated before registration.
Write pseudocode for a function `ValidatePassword` that takes a string `Password` as a parameter and returns a boolean value (`TRUE` if the password is valid, and `FALSE` otherwise).
To be valid, the password must satisfy the following criteria: - It must be between 8 and 15 characters long (inclusive). - It must contain at least one uppercase alphabetical character (`'A'` to `'Z'`). - It must contain at least one lowercase alphabetical character (`'a'` to `'z'`). - It must contain at least one numeric digit character (`'0'` to `'9'`). - It must not contain any space characters (`' '`).
You must use standard built-in functions: - `LENGTH(String1 : STRING) RETURNS INTEGER` - `MID(String1 : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING`
You must declare all local variables used. Ensure your pseudocode follows standard Cambridge International syllabus conventions.
FOR Index <- 1 TO Length CurrentChar <- MID(Password, Index, 1) IF CurrentChar >= "A" AND CurrentChar <= "Z" THEN HasUpper <- TRUE ELSEIF CurrentChar >= "a" AND CurrentChar <= "z" THEN HasLower <- TRUE ELSEIF CurrentChar >= "0" AND CurrentChar <= "9" THEN HasDigit <- TRUE ELSEIF CurrentChar = " " THEN HasSpace <- TRUE ENDIF ENDFOR
IF HasUpper AND HasLower AND HasDigit AND NOT HasSpace THEN RETURN TRUE ELSE RETURN FALSE ENDIF ENDFUNCTION ```
PastPaper.markingScheme
Award marks as follows (Max 11.25 marks total): - **1 mark**: Correct function header with parameter, return type, and correct `ENDFUNCTION`. - **1 mark**: Correctly declaring all local variables with appropriate data types (`BOOLEAN`, `INTEGER`, `CHAR`). - **1 mark**: Initializing all logical flags (`HasUpper`, `HasLower`, `HasDigit`, `HasSpace`) to `FALSE` (or correct initial values). - **1 mark**: Checking length constraint to be between 8 and 15 inclusive (returning `FALSE` immediately or setting flag). - **1 mark**: Setting up a loop from 1 to the length of the password string. - **1 mark**: Correct use of the `MID` function to extract a single character at the current index. - **1 mark**: Correct verification of uppercase characters (`'A'` to `'Z'`) and setting flag. - **1 mark**: Correct verification of lowercase characters (`'a'` to `'z'`) and setting flag. - **1 mark**: Correct verification of digit characters (`'0'` to `'9'`) and setting flag. - **1 mark**: Correct verification of spaces and setting flag. - **1 mark**: Final check of all combined boolean flags and returning correct outcome. - **0.25 mark**: Correct variable scopes and neat pseudocode notation.
A 2D array `Grid` has dimensions 10 rows by 10 columns, indexed from 1 to 10 for both row and column. Each cell of the array contains a single character: `'X'`, `'O'`, or `'.'`.
Write pseudocode for a procedure `FindSequences` that takes the array `Grid` as a parameter. The procedure must search the entire array to find all occurrences of exactly three consecutive `'X'` characters in a straight line. The consecutive characters can be: 1. Horizontal (from left to right in the same row). 2. Vertical (from top to bottom in the same column).
The procedure must output the starting row and column coordinates, along with the direction of the sequence (either `"Horizontal"` or `"Vertical"`), for every such sequence found.
Do not worry about overlapping sequences (e.g., if there are four `'X'`s in a row, it is acceptable to report a sequence starting at column 1 and another starting at column 2). Make sure your checks do not attempt to access array indices out of bounds.
You must declare all local variables used.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
```pseudocode PROCEDURE FindSequences(Grid : ARRAY OF CHAR) DECLARE Row : INTEGER DECLARE Col : INTEGER
// Check horizontal sequences FOR Row <- 1 TO 10 FOR Col <- 1 TO 8 IF Grid[Row, Col] = "X" AND Grid[Row, Col + 1] = "X" AND Grid[Row, Col + 2] = "X" THEN OUTPUT "Sequence found at Row: ", Row, ", Col: ", Col, ", Direction: Horizontal" ENDIF ENDFOR ENDFOR
// Check vertical sequences FOR Row <- 1 TO 8 FOR Col <- 1 TO 10 IF Grid[Row, Col] = "X" AND Grid[Row + 1, Col] = "X" AND Grid[Row + 2, Col] = "X" THEN OUTPUT "Sequence found at Row: ", Row, ", Col: ", Col, ", Direction: Vertical" ENDIF ENDFOR ENDFOR ENDPROCEDURE ```
PastPaper.markingScheme
Award marks as follows (Max 11.25 marks total): - **1 mark**: Correct procedure declaration with 2D array parameter and `ENDPROCEDURE`. - **1 mark**: Declaring loop variables `Row` and `Col` with the correct type (`INTEGER`). - **1 mark**: Outer loop for horizontal check iterating row from 1 to 10. - **1 mark**: Inner loop for horizontal check iterating column from 1 to 8. - **1 mark**: Preventing horizontal out-of-bound errors (ensuring column does not exceed 8). - **1 mark**: Correct horizontal conditional logic comparing three successive cells (`Grid[Row, Col]`, `Grid[Row, Col+1]`, `Grid[Row, Col+2]`). - **1 mark**: Correct horizontal sequence output matching specifications. - **1 mark**: Outer loop for vertical check iterating column from 1 to 10. - **1 mark**: Inner loop for vertical check iterating row from 1 to 8. - **1 mark**: Correct vertical conditional logic comparing three successive cells (`Grid[Row, Col]`, `Grid[Row+1, Col]`, `Grid[Row+2, Col]`). - **1 mark**: Correct vertical sequence output matching specifications. - **0.25 mark**: Good structure and logical layout.
A text file named `"Sales.txt"` contains transaction records. Each line of the file contains information about a single sale in a comma-separated format: `,,`
An example of a line from the file is: `"CUST4022,Electronics,125.50"`
Write pseudocode for a procedure `SummarizeSales`. The procedure must read the contents of `"Sales.txt"` line by line and perform the following tasks: 1. Calculate and output the total sales amount for the `"Electronics"` category. 2. Find the Customer ID that made the single transaction with the highest sales amount across all categories. 3. Output the customer ID and the amount of this highest transaction.
Assume: - The file exists, contains at least one line, and is not empty. - There are no spaces around the commas. - You can use the standard built-in function `STR_TO_NUM(String1 : STRING) RETURNS REAL` to convert numeric strings to real values. - Other available string functions: - `LENGTH(String1 : STRING) RETURNS INTEGER` - `MID(String1 : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING`
You must declare all local variables. Show the file operations clearly (opening, reading, closing) using standard Cambridge pseudocode.
WHILE NOT EOF("Sales.txt") READFILE "Sales.txt", Line
// Find positions of commas Comma1 <- 0 Comma2 <- 0 FOR Index <- 1 TO LENGTH(Line) IF MID(Line, Index, 1) = "," THEN IF Comma1 = 0 THEN Comma1 <- Index ELSE Comma2 <- Index ENDIF ENDIF ENDFOR
Award marks as follows (Max 11.25 marks total): - **1 mark**: Opening "Sales.txt" in READ mode and closing it using correct commands. - **1 mark**: Implementing a `WHILE NOT EOF("Sales.txt")` loop with a correct `READFILE` operation. - **1 mark**: Initializing accumulator variables correctly (`TotalElectronics` to `0.0`, `MaxAmount` to `0.0` or `-1.0`). - **2 marks**: Parsing loop logic to locate the first and second commas in the line (1 mark for scanning loop, 1 mark for tracking two distinct indices). - **1 mark**: Extracting `CustID` correctly from start to first comma minus one. - **1 mark**: Extracting `Category` correctly between the first and second comma. - **1 mark**: Extracting `AmountStr` correctly and parsing to a numeric type using `STR_TO_NUM`. - **1 mark**: Checking if `Category` matches "Electronics" and updating accumulator total. - **1 mark**: Verifying if the amount is greater than `MaxAmount` and storing the higher values. - **1 mark**: Correct outputs with suitable descriptive strings outside the file processing loop. - **0.25 mark**: Correct variable declaration block for all local variables used.
Using Boolean algebra theorems and laws, simplify the following expression to show that: \( \overline{(A + \overline{B})} \cdot \overline{(\overline{A} \cdot C)} + A \cdot B = B \cdot (A + \overline{C}) \) where the dot represents AND and the bar represents NOT. State the name of the law or theorem used at each step.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Step 1: Apply De Morgan's Law to the first term \( \overline{(A + \overline{B})} \) to get \( \overline{A} \cdot \overline{\overline{B}} = \overline{A} \cdot B \). Step 2: Apply De Morgan's Law and Double Negation to the second term \( \overline{(\overline{A} \cdot C)} \) to get \( \overline{\overline{A}} + \overline{C} = A + \overline{C} \). Step 3: Substitute these back into the expression: \( (\overline{A} \cdot B) \cdot (A + \overline{C}) + A \cdot B \). Step 4: Apply the Distributive Law to expand: \( \overline{A} \cdot B \cdot A + \overline{A} \cdot B \cdot \overline{C} + A \cdot B \). Step 5: Since \( \overline{A} \cdot A = 0 \) (Inverse Law), the first term becomes \( 0 \cdot B = 0 \). The expression becomes \( \overline{A} \cdot B \cdot \overline{C} + A \cdot B \). Step 6: Factor out B using the Distributive Law: \( B \cdot (\overline{A} \cdot \overline{C} + A) \). Step 7: Apply the Distributive Law inside the parentheses: \( \overline{A} \cdot \overline{C} + A = (A + \overline{A}) \cdot (A + \overline{C}) \). Step 8: Since \( A + \overline{A} = 1 \) (Inverse Law), this simplifies to \( 1 \cdot (A + \overline{C}) = A + \overline{C} \). Step 9: Multiply back by B to get the final simplified expression: \( B \cdot (A + \overline{C}) \).
PastPaper.markingScheme
1 mark for correctly applying De Morgan's Law to \( \overline{(A + \overline{B})} \) to get \( \overline{A} \cdot B \). 1 mark for correctly applying De Morgan's Law to \( \overline{(\overline{A} \cdot C)} \) to get \( A + \overline{C} \). 1 mark for expanding the terms to get \( \overline{A} \cdot B \cdot A + \overline{A} \cdot B \cdot \overline{C} + A \cdot B \). 1 mark for simplifying \( \overline{A} \cdot B \cdot A \) to 0. 1 mark for factoring B and applying the distributive law to \( \overline{A} \cdot \overline{C} + A \). 1.25 marks for achieving the final expression \( B \cdot (A + \overline{C}) \) with all steps clearly documented with their respective laws.
A real number is to be stored using a normalized floating-point representation with an 8-bit mantissa and a 4-bit exponent. Both mantissa and exponent are stored in two's complement form. Convert the denary value \( -6.75 \) into this normalized floating-point format. Show all your working, including how you derived the mantissa and exponent.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Step 1: Convert the magnitude \( 6.75 \) to binary: \( 6 = 110_{2} \) and \( 0.75 = 0.11_{2} \), so \( 6.75 = 110.11_{2} \). Step 2: Represent as a positive binary value with 8 bits of precision: \( 0110.1100 \). Step 3: Find the two's complement of this binary value to represent \( -6.75 \). One's complement is \( 1001.0011 \). Adding 1 gives \( 1001.0100 \). Step 4: Normalize this negative binary value. Negative normalized floating-point numbers must start with 1 and 0 (i.e., \( 1.0 \)). Shift the binary point to the left by 3 places to get \( 1.0010100 \times 2^3 \). Step 5: Convert the exponent \( +3 \) into 4-bit two's complement, which is \( 0011 \). Step 6: Extract the final components. The 8-bit mantissa is \( 10010100 \) and the 4-bit exponent is \( 0011 \).
PastPaper.markingScheme
1 mark for correctly converting magnitude 6.75 to binary (110.11). 2 marks for obtaining the correct two's complement representation of -6.75 (1001.0100). 2 marks for correctly shifting/normalizing the mantissa to 1.0010100 and identifying the exponent as +3. 1.25 marks for writing the final correct 8-bit mantissa (10010100) and 4-bit exponent (0011).
A logic system has four inputs: \( A, B, C, \) and \( D \). The system output is active (1) for the following minterms: \( \sum(1, 3, 5, 7, 8, 9, 12, 13) \). (a) Construct a Karnaugh Map (K-map) for this system. (b) Use the K-map to derive a simplified Sum-of-Products (SOP) expression for the output. Show your grouping clearly.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Step 1: Construct the K-map with AB as rows (00, 01, 11, 10) and CD as columns (00, 01, 11, 10). Fill the cells corresponding to the minterms with 1: cells (00,01), (00,11), (01,01), (01,11), (11,00), (11,01), (10,00), (10,01) are all 1. All other cells are 0. Step 2: Identify groups of 1s. Group 1 is a 2x2 group of four 1s containing minterms 1, 3, 5, and 7. This group simplifies to \( \overline{A}D \). Group 2 is a 2x2 group of four 1s containing minterms 12, 13, 8, and 9. This group simplifies to \( A\overline{C} \). Step 3: Combine these two terms to get the simplified SOP expression: \( F = \overline{A}D + A\overline{C} \).
PastPaper.markingScheme
2 marks for drawing a correctly labeled K-map with all 1s and 0s in correct positions. 2 marks for correctly identifying and looping the two 2x2 groups. 2.25 marks for writing the correct simplified SOP expression F = A'D + AC' (1 mark for A'D, 1 mark for AC', 0.25 marks for putting them together).
Perform the addition of the following two normalized floating-point numbers: \( X = \text{Mantissa: } 0.1011000, \text{ Exponent: } 0010 \) and \( Y = \text{Mantissa: } 0.1100000, \text{ Exponent: } 0000 \). Both numbers use a normalized 8-bit mantissa and a 4-bit exponent, both in two's complement form. Show all your working. Your final answer must be in the same normalized floating-point format.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Step 1: Extract exponents. Exponent of \( X \) is \( 0010 \) (+2) and exponent of \( Y \) is \( 0000 \) (0). Step 2: Align exponents by shifting the mantissa of \( Y \) right by 2 places to match \( X \)'s exponent of 2. Original \( Y \) mantissa \( 0.1100000 \) becomes \( 0.0011000 \). Step 3: Perform binary addition of the mantissas: \( 0.1011000 + 0.0011000 = 0.1110000 \). Step 4: Verify the result is normalized. Since the first two bits are different (0 and 1), the sum \( 0.1110000 \) is already normalized. Step 5: State the final representation with exponent \( 0010 \). Final Mantissa: \( 0.1110000 \), Exponent: \( 0010 \).
PastPaper.markingScheme
1 mark for identifying the exponents (+2 and 0). 2 marks for correctly aligning the mantissa of Y by shifting it right by 2 places to get 0.0011000. 2 marks for adding the mantissas correctly to get 0.1110000. 1.25 marks for identifying that the result is normalized and correctly stating the final mantissa (0.1110000) and exponent (0010).
PastPaper.question 5 · Object Oriented Paradigm
5.5 PastPaper.marks
A transport logistics company manages various vehicles. An existing superclass `Vehicle` has the private attributes `Registration` (String) and `DailyRate` (Real).
A new class `ElectricCar` is created which inherits from the `Vehicle` class. It has an additional private attribute `BatteryCapacity` (Integer).
Write a pseudocode class definition for `ElectricCar`, including its constructor.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To declare a subclass in CIE pseudocode, use the `INHERITS` keyword: `CLASS ElectricCar INHERITS Vehicle`. Declaring private variables inside the class: `PRIVATE BatteryCapacity : INTEGER`. The constructor `PUBLIC METHOD NEW(...)` must receive attributes for both the parent class and the child class. Within the constructor, invoke the superclass constructor using `SUPER.NEW(Reg, Rate)` and then assign the local property `BatteryCapacity <- Capacity`.
PastPaper.markingScheme
1 mark: Correct class header specifying inheritance (`CLASS ElectricCar INHERITS Vehicle`). 1 mark: Declaring private attribute `BatteryCapacity : INTEGER`. 1 mark: Constructor header `PUBLIC METHOD NEW(...)` with parameters for registration, daily rate, and battery capacity. 1 mark: Invoking superclass constructor passing parent class values (`SUPER.NEW(...)`). 1 mark: Correctly assigning capacity parameter to the subclass attribute `BatteryCapacity`. 0.5 mark: Correct closing structures (`ENDMETHOD` and `ENDCLASS`).
A library software system stores records of type `BookRecord` in a random-access file named `BookFile.dat`.
1. Define the record structure `BookRecord` in pseudocode. It contains the following fields: `ISBN` (string), `Title` (string), and `Available` (boolean). 2. Write a pseudocode procedure `WriteRecord(Address : INTEGER, RecordData : BookRecord)` that opens `BookFile.dat` for random access, writes the given record data at the position specified by `Address`, and closes the file.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
First, we declare a record type with `TYPE BookRecord` and fields, ending with `ENDTYPE`. Second, we write the procedure structure. In pseudocode, file opening for random/direct access is done using `OPENFILE \"BookFile.dat\" FOR RANDOM`. The pointer is positioned at the record address using `SEEK \"BookFile.dat\", Address`. We write the record data with `WRITEFILE \"BookFile.dat\", RecordData` and finally close the file with `CLOSEFILE \"BookFile.dat\"`.
PastPaper.markingScheme
Part 1 (1.5 Marks): - 0.5 mark: Defining record structure with `TYPE BookRecord` and `ENDTYPE`. - 1 mark: Declaring all three fields with correct data types (`ISBN: STRING`, `Title: STRING`, `Available: BOOLEAN`).
Part 2 (4 Marks): - 1 mark: Procedure header with correct parameters (`Address` and `RecordData`). - 1 mark: Correct file open syntax for random/direct access (`OPENFILE "BookFile.dat" FOR RANDOM`). - 1 mark: Correct syntax to navigate to the record position (`SEEK` or index parameter inside `WRITEFILE`). - 1 mark: Correct file write and close statements (`WRITEFILE "BookFile.dat", RecordData` and `CLOSEFILE "BookFile.dat"`).
PastPaper.question 7 · Object Oriented Paradigm
5.5 PastPaper.marks
A flight booking system has two classes: `Passenger` and `Flight`.
1. A `Flight` object contains an array of 150 `Passenger` objects. Explain whether this relationship represents aggregation or composition, justifying your answer. 2. Write the pseudocode class definition for `Flight`, including only the private attribute `PassengerList` (an array of 150 `Passenger` objects) and its constructor which instantiates the array.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Aggregation is defined by the life cycle of the contained object. If the container (Flight) is destroyed, the contained objects (Passengers) still exist. This fits the scenario because passengers continue to exist outside the flight. 2. The class structure contains: `CLASS Flight`, followed by `PRIVATE PassengerList : ARRAY[1..150] OF Passenger`, and a constructor `PUBLIC METHOD NEW()` initializing or preparing the references inside the array.
PastPaper.markingScheme
Part 1 (1.5 Marks): - 1 mark: Identifying relationship as Aggregation. - 0.5 mark: Correct justification (passengers can exist independently of the flight object / flight cancellation does not destroy the passenger).
Part 2 (4 Marks): - 1 mark: Class header `CLASS Flight` and class footer `ENDCLASS`. - 1 mark: Declaration of private array attribute `PassengerList : ARRAY[1..150] OF Passenger`. - 1 mark: Constructor declaration `PUBLIC METHOD NEW()` / `ENDMETHOD`. - 1 mark: Loop or statement block initializing array elements.
A structured text file `Students.txt` contains student names and test scores. Every student entry takes up exactly two lines: - Line 1: Student Name (e.g. \"Alice\") - Line 2: Student Score (e.g. \"85\")
Write a pseudocode procedure `FilterPasses(MinScore : INTEGER)` that reads data from `Students.txt`, and writes the names of all students who achieved a score greater than or equal to `MinScore` to a new text file named `Passed.txt`.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The procedure must open `Students.txt` in read mode and `Passed.txt` in write mode. It then processes the file line-by-line using a `WHILE NOT EOF` loop. Inside, we read two lines in sequence (first string for Name, second string for Score). We convert the score string into an integer and compare it to `MinScore`. If it meets the threshold, we write the name to `Passed.txt`. Finally, we close both files.
PastPaper.markingScheme
1 mark: Open both files with correct file modes (read for 'Students.txt' and write for 'Passed.txt'). 1 mark: Loop while not at the end of the file 'Students.txt' (`WHILE NOT EOF("Students.txt")`). 1 mark: Correctly reading two lines consecutively inside the loop (first name, then score). 1 mark: Correct comparison of score with `MinScore` (including casting/converting string to number if needed). 1 mark: Correctly writing only the student's name to 'Passed.txt' inside the selection statement. 0.5 mark: Closing both files correctly upon loop completion.
PastPaper.question 9 · Object Oriented Paradigm
5.5 PastPaper.marks
An inheritance hierarchy includes a superclass `Employee` with a method `CalculatePay() : REAL`. A subclass `CommissionEmployee` inherits from `Employee` and has private attributes `BaseSalary` (Real) and `SalesCount` (Integer).
1. Explain the concept of polymorphism within object-oriented programming. 2. Write the pseudocode implementation of the subclass method `CalculatePay()` for `CommissionEmployee`. The method overrides the superclass method, calculating pay as the `BaseSalary` plus an additional $45 for each sale made (`SalesCount`).
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Polymorphism allows subclasses to redefine inherited methods (overriding). At runtime, dynamic binding ensures the correct version of the method is executed depending on the instantiated object. 2. In pseudocode, a subclass method overriding a superclass method has the same signature. Inside `CalculatePay()`, the commission is calculated as `SalesCount * 45.0` and added to `BaseSalary`, returning the resulting value.
PastPaper.markingScheme
Part 1 (1.5 Marks): - 1 mark: Polymorphism allows methods of the same name to behave differently depending on the class object calling them. - 0.5 mark: Resolution happens dynamically at runtime (dynamic binding).
Part 2 (4 Marks): - 1 mark: Correct method header `PUBLIC METHOD CalculatePay() RETURNS REAL` (optionally with OVERRIDE keyword). - 1 mark: Calculate correct commission value (`SalesCount * 45` or `SalesCount * 45.0`). - 1 mark: Adding `BaseSalary` to the calculated commission. - 1 mark: Returning the total pay value and ending the method cleanly (`RETURN` and `ENDMETHOD`).
PastPaper.question 10 · Object Oriented Paradigm
5.5 PastPaper.marks
An interactive map system contains a variety of interactive nodes. An abstract class `MapNode` is created as the parent of all nodes.
1. State two differences between an abstract class and an interface. 2. Write the pseudocode class definition for the abstract class `MapNode`. It has a private attribute `NodeID` (String), an abstract method `OnTrigger()` that returns a boolean value, and a constructor that sets `NodeID`.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Key differences: abstract classes can have member attributes (state) and fully implemented methods. Interfaces only have abstract method definitions. Subclasses are limited to single inheritance from abstract classes but multiple implementations of interfaces. 2. The class is declared with `ABSTRACT CLASS MapNode`. Inside, we declare the private attribute and write the constructor. The abstract method has the `ABSTRACT` keyword and no body, only a signature: `ABSTRACT METHOD OnTrigger() RETURNS BOOLEAN`.
PastPaper.markingScheme
Part 1 (2 Marks): - 1 mark: Abstract class can have fields/attributes (state), while an interface only declares method signatures/no state. - 1 mark: A class can only inherit from one abstract class but can implement multiple interfaces.
Part 2 (3.5 Marks): - 1 mark: Class header `ABSTRACT CLASS MapNode` and correct declaration of private `NodeID : STRING`. - 1 mark: Correct constructor definition `PUBLIC METHOD NEW(ID : STRING)` assigning `NodeID <- ID`. - 1 mark: Correct abstract method signature `ABSTRACT METHOD OnTrigger() RETURNS BOOLEAN` with no implementation body. - 0.5 mark: Correct closing tags (`ENDMETHOD` and `ENDCLASS`).
A direct-access/random file `Stock.dat` stores product details of type `StockRecord` at addresses determined by a hash function. The product ID is a 4-digit integer from 1000 to 9999.
The hash function is defined as: \(Hash(ProductID) = (ProductID \pmod{500}) + 1\)
Write a pseudocode function `FindProduct(TargetID : INTEGER) RETURNS StockRecord` that calculates the file address using the hash function, opens `Stock.dat` for random access, retrieves the record, and returns the record if its product ID matches `TargetID`. If it does not match, it returns an empty/dummy record.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To fetch from a random file, we first calculate the index using modulo: `(TargetID MOD 500) + 1`. We then open the file `FOR RANDOM`, use `SEEK` to point to the calculated record address, and read the record with `READFILE`. After closing the file, we perform a verification check: if `TargetRecord.ProductID = TargetID`, we return the record; otherwise, we return a dummy record.
PastPaper.markingScheme
1 mark: Function header and correct return type (`RETURNS StockRecord`). 1 mark: Implementing the correct hash calculation `Address <- (TargetID MOD 500) + 1`. 1 mark: Opening file in random mode and moving pointer using `SEEK "Stock.dat", Address`. 1 mark: Reading the record data into a variable of type `StockRecord` and closing the file. 1 mark: Conditional check comparing retrieved record ID with `TargetID`, returning the record if matched. 0.5 mark: Handling the mismatch case by returning a dummy record and ending the function (`ENDFUNCTION`).
1. Explain why exception handling is necessary when implementing file access operations in an application. 2. Write a pseudocode block to open a binary file `Scores.dat` and read numeric integers until the end of the file is reached, summing the values. The code must implement exception handling using `TRY ... EXCEPT ... ENDTRY` block syntax to catch any file error (e.g., file not found or corrupted file) and display a user-friendly error message.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
1. Exception handling allows an application to respond to runtime failures (such as missing files or read failures) gracefully instead of terminating unexpectedly. 2. The code structure contains a `TRY` block that attempts to open, iterate through reading lines using `WHILE NOT EOF`, and close the file. Any exception thrown drops the flow into the `EXCEPT` block, outputting a clear diagnostic message.
PastPaper.markingScheme
Part 1 (2 Marks): - 1 mark: File systems are external to the program execution and files may be missing/locked/corrupt outside the developer's control. - 1 mark: Exception handling prevents hard program crashes and allows graceful error recovery or resource cleanup.
Part 2 (3.5 Marks): - 1 mark: Correct `TRY ... EXCEPT ... ENDTRY` block structure. - 1 mark: Proper file opening, reading loop, and accumulation logic within the TRY block. - 1 mark: Catching errors in the EXCEPT block and outputting an appropriate diagnostic message. - 0.5 mark: Safely closing the file within the normal flow or block structure.
PastPaper.question 13 · open
5.5 PastPaper.marks
A computer game uses an object-oriented approach to manage players currently waiting in a lobby.
The class `GameCharacter` has private attributes `CharacterID` (STRING), `Score` (INTEGER), and `Level` (INTEGER). It contains public getter methods: `GetCharacterID()`, `GetScore()`, and `GetLevel()` which return their respective attributes.
A global array `Lobby` is declared as: `DECLARE Lobby : ARRAY[1:100] OF GameCharacter`
Write pseudocode for a procedure `ArchiveLobby(FileName : STRING)` that: 1. Opens the text file specified by `FileName` for writing. 2. Loops through the entire `Lobby` array. 3. Checks if a character is active (a character is active if their `CharacterID` is not equal to `""`). 4. For each active character, writes their `CharacterID`, `Score`, and `Level` on three separate lines to the file. 5. Closes the file when complete.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
To implement the procedure `ArchiveLobby` according to the CAIE 9618 pseudocode syllabus: 1. **Procedure Header**: Define `PROCEDURE ArchiveLobby(FileName : STRING)` and match it with a corresponding `ENDPROCEDURE`. 2. **File Initialization**: Use `OPENFILE FileName FOR WRITE` to open the text file for writing. 3. **Looping**: Create a `FOR` loop iterating from 1 to 100 to access each index of the `Lobby` array. 4. **Validation Check**: Inside the loop, check if the current `GameCharacter` object has an active ID using the getter method: `Lobby[Index].GetCharacterID() <> ""`. 5. **File Writing**: Write each attribute sequentially to the file using `WRITEFILE`. Since `Score` and `Level` are integers, we use `NUM_TO_STR()` to ensure standard text compatibility. 6. **File Termination**: Close the file after the loop finishes using `CLOSEFILE FileName`.
PastPaper.markingScheme
Marks are awarded as follows: - **1 mark** for correct procedure header and terminator containing the correct string parameter. - **1 mark** for opening (`OPENFILE ... FOR WRITE`) and closing (`CLOSEFILE`) the file correctly. - **1 mark** for a loop that successfully iterates through all 100 elements of the array. - **1 mark** for calling the getter `GetCharacterID()` on the correct array elements and comparing it to `""`. - **1.5 marks** for writing all three attributes to the file sequentially on separate lines (0.5 marks per attribute). Note: Direct usage of integer return values or explicit conversion using `NUM_TO_STR()` is acceptable.
Paper 42 Practical
Complete all three development tasks in Java, Python, or Visual Basic. Save work in evidence.doc.
3 PastPaper.question · 75 PastPaper.marks
PastPaper.question 1 · Program implementation & Screen testing
25 PastPaper.marks
A binary tree is to be implemented as an array of nodes. Each node is represented as an instance of a class `Node`.
The class `Node` has three private attributes: - `Data` (String) - `LeftPointer` (Integer) - `RightPointer` (Integer)
1. Write program code to declare the class `Node`. Include: - A constructor that initializes `Data` to an empty string, and the pointers to `-1`. - Public getter and setter methods for all three attributes. [5 marks]
2. Declaring global variables: - Declare a 1D array `Tree` of 15 elements of type `Node`. - Declare an integer `RootPointer` initialized to `-1`. - Declare an integer `FreePointer` initialized to `0`. Write code to initialize the `Tree` array such that each element's `LeftPointer` points to the next free element (creating a free list), with the last element's `LeftPointer` set to `-1`. The `RightPointer` and `Data` should remain initialized as per the constructor. [4 marks]
3. Write a procedure `InsertNode(NewData)` that: - Checks if the tree is full (i.e., `FreePointer` is `-1`). If full, outputs an error message. - If not full, retrieves the node at `FreePointer`, sets its `Data` to `NewData`, and updates `FreePointer` to the next free node. - If `RootPointer` is `-1`, sets `RootPointer` to point to this new node. - Otherwise, traverses the tree from `RootPointer` to find the correct insertion position (as a binary search tree), and updates the appropriate parent pointer. [8 marks]
4. Write a recursive procedure `InOrder(Pointer)` that performs an in-order traversal of the tree, printing the `Data` of each node. [4 marks]
5. Write a main program that: - Initializes the tree. - Inserts the following strings in this order: "Mango", "Apple", "Banana", "Peach", "Plum", "Cherry". - Calls `InOrder(RootPointer)` to display the elements. Take a screenshot of the output. [4 marks]
Save your program code and screenshot in your evidence document.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The binary search tree is constructed using a 1D array of objects. The free list is managed using the `LeftPointer` of unused nodes. When inserting, the `FreePointer` is updated to point to the next available free node, and the node's properties are overwritten. Traversing down from the root, we check if the new data is lexicographically smaller or larger than the current node's data and route accordingly, updating the correct parent pointer. `InOrder` uses recursive traversal: left child, current node, right child.
PastPaper.markingScheme
- Class Node definition: 1 mark - Private attributes initialization in constructor: 1 mark - Getter and Setter methods for Data and both pointers: 3 marks - Declaring global Tree array, RootPointer, and FreePointer: 1 mark - InitializeTree function setting FreePointer chain correctly: 3 marks - InsertNode checking if tree is full: 1 mark - Retrieving free index and advancing FreePointer: 2 marks - Correctly traversing the tree to find parent node: 3 marks - Correctly updating left or right parent pointer: 2 marks - Recursive InOrder traversal function: 4 marks - Main program inserting test values and calling InOrder traversal: 3 marks - Correct program operation and screenshot matching alphabetical order output: 1 mark
PastPaper.question 2 · Program implementation & Screen testing
25 PastPaper.marks
An object-oriented tracking system is being designed for a shipping company. The system tracks standard and express parcels.
1. Define a base class `Parcel` with the following: [8 marks] - Private attributes: - `TrackingID` (String) - `Weight` (Real) - `BaseCost` (Real) - A constructor that takes three parameters to initialize these attributes. - Getter methods for all attributes. - A method `CalculateCost()` that returns the total delivery cost, calculated as `Weight * BaseCost`.
2. Define a subclass `ExpressParcel` that inherits from `Parcel` and adds the following: [7 marks] - Private attribute: - `DaysToDeliver` (Integer) - A constructor that takes four parameters to initialize both standard and express attributes. - A getter method for `DaysToDeliver`. - Overrides the `CalculateCost()` method: - If `DaysToDeliver` is 1, the total delivery cost is the base parcel cost multiplied by `1.5`. - If `DaysToDeliver` is 2, the total delivery cost is the base parcel cost multiplied by `1.2`. - Otherwise, it returns the base parcel cost.
3. Write a main program to: [10 marks] - Declare a 1D array/list of 5 elements of type `Parcel`. - Instantiate the following 5 objects into the array: - A standard parcel with tracking ID "P101", weight 2.5 kg, and base cost $10.00. - An express parcel with tracking ID "E201", weight 1.5 kg, base cost $12.00, and 1 day to deliver. - An express parcel with tracking ID "E202", weight 3.0 kg, base cost $8.50, and 2 days to deliver. - A standard parcel with tracking ID "P102", weight 5.0 kg, and base cost $9.00. - An express parcel with tracking ID "E203", weight 2.0 kg, base cost $11.00, and 3 days to deliver. - Loop through the array to display each parcel's `TrackingID` and its total calculated cost. - Test your program and capture a screenshot of the output.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
We define standard class inheritance structure. The subclass inherits from `Parcel` and uses the `super()` method (or base class invocation) to access attributes in the constructor and call the base implementation of `CalculateCost()` before applying custom scaling modifiers. Declaring a single polymorphic array of type `Parcel` is standard and demonstrates object-oriented design.
PastPaper.markingScheme
- Base class `Parcel` definition with private attributes: 2 marks - Constructor initializing all fields: 1 mark - Three getter methods correctly implemented: 2 marks - `CalculateCost` method implemented correctly: 3 marks - Subclass `ExpressParcel` correctly inherits from `Parcel`: 1 mark - Subclass constructor correctly calls superclass constructor: 2 marks - Subclass contains private `DaysToDeliver` and getter: 1 mark - Overridden `CalculateCost` in subclass with correct conditional multipliers: 3 marks - Array of `Parcel` declared with 5 items: 1 mark - Initialization of all 5 items with correct types and parameters: 3 marks - Loop iterating through array calling overridden methods (polymorphism): 3 marks - Correct output formatting and screenshot: 3 marks
PastPaper.question 3 · Program implementation & Screen testing
25 PastPaper.marks
A text file named `Items.txt` contains stock data. Each line of the file contains an item code and its stock count, separated by a comma. There are exactly 10 lines of data in the file.
1. Define a class `Item` with public fields `ItemCode` (String) and `StockCount` (Integer). Declare a global 1D array named `Inventory` of 10 elements of type `Item`. [3 marks]
2. Write a function `LoadData()` that reads the data from `Items.txt` and stores each record into the `Inventory` array. [6 marks]
3. Write a procedure `BubbleSort()` that sorts the `Inventory` array in descending order of `StockCount` using a standard bubble sort algorithm. [7 marks]
4. Write a recursive function `RecursiveSearch(Low, High, TargetStock)` that performs a binary search to find an item with the `TargetStock` count. Because the array is sorted in descending order, the search logic must account for this. The function must return the index of the item if found, and `-1` if not. [6 marks]
5. Write a main program that: - Calls `LoadData()` - Sorts the array using `BubbleSort()` - Outputs the sorted inventory (ItemCode and StockCount) - Prompts the user to search for a stock count, calls `RecursiveSearch`, and outputs the matching `ItemCode` if found, or an appropriate message if not found. [3 marks]
Save your program code and screenshot of the output in your evidence document.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
We load data using standard Python file reading operations, parsing each line and casting the second element as an integer before initializing the `Item` object. For descending bubble sort, we compare `Inventory[j].StockCount < Inventory[j+1].StockCount`. The recursive binary search uses descending logic: if the middle element is less than the target, we look towards the lower index indices (left) because larger values are at the start of the array.
PastPaper.markingScheme
- Item class declaration with fields: 1 mark - Declaration of global array Inventory: 2 marks - LoadData function opening and reading line by line: 2 marks - Split data and correctly instantiate Item into Inventory array: 3 marks - File close and error handling: 1 mark - BubbleSort nested loops: 3 marks - BubbleSort correct descending swap comparison logic: 3 marks - Swap logic working correctly: 1 mark - RecursiveSearch base case (Low > High return -1): 1 mark - Calculate Mid and check if target found: 1 mark - Recursive calls adjusting Low/High correctly for descending array order: 3 marks - Recursive function returns the final value: 1 mark - Main program workflow calls LoadData and BubbleSort: 1 mark - Print sorted inventory loop: 1 mark - Search invocation and output formatting: 1 mark