IB DP · PastPaper.sampleTitle

MetadataPastPaper.sampleTitle

Thinka May 2024 SL (TZ2) IB Diploma Programme-Style Mock — Computer Science

115 PastPaper.marks150 PastPaper.minutes2024
An original Thinka practice paper modelled on the structure and difficulty of the May 2024 SL (TZ2) IB Diploma Programme Computer Science paper. Not affiliated with or reproduced from IB.

Paper 1 Section A

Answer all questions.
12 PastPaper.question · 24.959999999999994 PastPaper.marks
PastPaper.question 1 · Short Answer
2.08 PastPaper.marks
Identify one disadvantage of using direct changeover as a method of system implementation.
PastPaper.showAnswers

PastPaper.workedSolution

Direct changeover involves completely shutting down the legacy system and immediately launching the new system. Because there is no period of overlap or redundant operation, any unexpected failure in the new system can lead to severe data loss or total disruption of business activities since there is no backup system active.

PastPaper.markingScheme

Award [1 mark] for identifying the high risk or lack of a fallback system. Award [1 mark] for explaining the consequence, such as immediate data loss, business disruption, or operational downtime.
PastPaper.question 2 · Short Answer
2.08 PastPaper.marks
Outline the function of the Program Counter (PC) in the CPU fetch-execute cycle.
PastPaper.showAnswers

PastPaper.workedSolution

The Program Counter (PC) is a dedicated register within the CPU. Its primary role is to store the memory address of the next instruction that needs to be executed. During the fetch stage, the CPU retrieves the instruction from the memory address specified by the PC, and the PC is subsequently incremented (or updated in the case of a jump/branch) to point to the next instruction in sequence.

PastPaper.markingScheme

Award [1 mark] for stating that it stores the memory address of the next instruction to be executed. Award [1 mark] for explaining that it increments or updates to point to the subsequent instruction after a fetch.
PastPaper.question 3 · Short Answer
2.08 PastPaper.marks
State two advantages of packet switching compared to circuit switching for data transmission.
PastPaper.showAnswers

PastPaper.workedSolution

Unlike circuit switching, packet switching does not require a dedicated physical channel to be established. This allows multiple data streams to share the same transmission lines, leading to higher bandwidth efficiency. Additionally, if a router or node along the path fails, individual packets can dynamically reroute around the failure, making the transmission highly fault-tolerant.

PastPaper.markingScheme

Award [1 mark] for each valid advantage stated up to a maximum of [2 marks]. Acceptable answers include: more efficient bandwidth/channel usage, higher resilience/fault tolerance (alternative paths), cheaper implementation, or packets can be buffered if a bottleneck occurs.
PastPaper.question 4 · Short Answer
2.08 PastPaper.marks
Define the term abstraction as it applies to computational thinking.
PastPaper.showAnswers

PastPaper.workedSolution

In computational thinking, abstraction is a key problem-solving technique. It involves simplifying complex real-world situations by ignoring or hiding details that are irrelevant to the current task, allowing the developer to focus purely on the core conceptual elements and high-level logic.

PastPaper.markingScheme

Award [1 mark] for mentioning the removal, hiding, or filtering of unnecessary/irrelevant details. Award [1 mark] for mentioning the focus on core, essential, or high-level characteristics of the problem.
PastPaper.question 5 · Short Answer
2.08 PastPaper.marks
Distinguish between a class and an object in object-oriented programming.
PastPaper.showAnswers

PastPaper.workedSolution

A class acts as a template or blueprint written in code that defines the attributes (data) and behaviors (methods) that all instances will possess. It does not contain live data in itself. An object, however, is a specific, instantiated entity that exists at runtime, allocating actual memory space to hold state-specific values for those attributes defined in the class.

PastPaper.markingScheme

Award [1 mark] for describing a class (e.g., static blueprint, template, definition). Award [1 mark] for describing an object (e.g., dynamic instance, concrete entity with state, memory-allocated instantiation of a class).
PastPaper.question 6 · Short Answer
2.08 PastPaper.marks
Outline one reason why a queue is an appropriate data structure for managing print jobs in a shared office printer.
PastPaper.showAnswers

PastPaper.workedSolution

A queue is a linear data structure that operates under the First-In-First-Out (FIFO) principle. For a shared office printer, this ensures a fair and predictable scheduling policy: the print job that was sent first is processed and printed first, preventing newer print jobs from overtaking older ones in the system queue.

PastPaper.markingScheme

Award [1 mark] for identifying the First-In-First-Out (FIFO) characteristic of a queue. Award [1 mark] for explaining why this ensures fairness or sequential processing order for print requests.
PastPaper.question 7 · Short Answer
2.08 PastPaper.marks
Explain what causes a page fault to occur in a computer system utilizing virtual memory.
PastPaper.showAnswers

PastPaper.workedSolution

Virtual memory is divided into blocks called pages. When a program references an address on a page that is not currently loaded in the physical RAM (main memory), the Memory Management Unit (MMU) cannot translate the virtual address. This triggers a hardware interrupt known as a page fault, signaling the operating system to retrieve the missing page from secondary storage (swap space/hard drive) and load it into RAM.

PastPaper.markingScheme

Award [1 mark] for stating that the requested virtual page/data is not present in the physical RAM/main memory. Award [1 mark] for explaining that this triggers an interrupt/request for the operating system to retrieve the page from secondary storage (disk/swap space).
PastPaper.question 8 · Short Answer
2.08 PastPaper.marks
In an automated greenhouse climate control system, outline the difference between the role of a sensor and the role of an actuator.
PastPaper.showAnswers

PastPaper.workedSolution

In a control system, sensors and actuators perform opposing but complementary functions. A sensor (e.g., a moisture or temperature sensor) measures physical state variables from the environment, converts them into signals, and sends them to the microprocessor. An actuator (e.g., a motorized window opener or heater) receives electrical signals/commands from the microprocessor and performs a physical action to change the state of the system.

PastPaper.markingScheme

Award [1 mark] for describing the sensor's role of gathering input / measuring environmental variables. Award [1 mark] for describing the actuator's role of taking physical action / output response to alter the environment based on system instructions.
PastPaper.question 9 · Short Answer
2.08 PastPaper.marks
Outline one potential compatibility issue that can arise when migrating data from a legacy system to a newly implemented system.
PastPaper.showAnswers

PastPaper.workedSolution

When migrating from a legacy system, the older software often uses proprietary, obsolete, or structured data formats (e.g., flat-file databases or legacy text encodings) that do not align with the modern, relational, or object-oriented database schema of the new system. Consequently, developers must write complex conversion scripts, which introduces the risk of data corruption, mismatching data types, or complete loss of metadata.

PastPaper.markingScheme

Award [1] for identifying a valid compatibility issue (e.g., mismatching database schemas, obsolete file formats, different character encoding standards).
Award [1] for outlining the consequence or implication of this issue during the migration process (e.g., requires data transformation scripts, risks data loss/corruption, or increases implementation time/cost).
PastPaper.question 10 · Short Answer
2.08 PastPaper.marks
State the role of the Program Counter (PC) during the fetch stage of the instruction cycle.
PastPaper.showAnswers

PastPaper.workedSolution

During the fetch stage, the CPU copies the memory address stored in the Program Counter (PC) to the Memory Address Register (MAR) so the instruction can be retrieved from RAM. Immediately after this address is sent (or during the fetch cycle), the PC is incremented by one (or by the instruction length) to point to the address of the next sequential instruction to be executed.

PastPaper.markingScheme

Award [1] for stating that the PC holds the memory address of the next instruction to be fetched/executed.
Award [1] for stating that the PC is incremented (by 1 or instruction size) to point to the next instruction.
PastPaper.question 11 · Short Answer
2.08 PastPaper.marks
Explain one benefit of dividing data into packets before transmitting it across a packet-switched network.
PastPaper.showAnswers

PastPaper.workedSolution

Dividing data into discrete packets allows for more efficient bandwidth utilization and error recovery. In the event of network congestion or packet loss, only the missing or damaged packet needs to be retransmitted by the sender, saving significant network overhead compared to resending the entire original file. Additionally, individual packets can take different physical routes to the destination, optimizing network load balancing.

PastPaper.markingScheme

Award [1] for identifying a valid benefit (e.g., selective retransmission, routing flexibility, avoiding channel monopolization).
Award [1] for explaining how this benefit occurs (e.g., only corrupted parts of the file are resent, or packets bypass congested routes to speed up delivery).
PastPaper.question 12 · Short Answer
2.08 PastPaper.marks
Outline how the concept of abstraction is applied when designing a computer simulation of a city's public transport system.
PastPaper.showAnswers

PastPaper.workedSolution

Abstraction simplifies complex real-world situations by ignoring non-essential details while keeping key characteristics. In a public transport simulation, physical details such as the model or color of the buses, individual driver profiles, and passenger names are omitted. Instead, the simulation only models critical parameters such as bus capacities, route distances, station locations, and scheduled arrival/departure times, which reduces computational complexity.

PastPaper.markingScheme

Award [1] for showing understanding of abstraction (e.g., filtering out unnecessary details / focusing only on important elements).
Award [1] for applying it directly to the public transport simulation context (e.g., ignoring bus aesthetic details or passenger identities, and modeling only transport schedules, capacities, or routes).

Paper 1 Section B

Answer all questions.
3 PastPaper.question · 45 PastPaper.marks
PastPaper.question 1 · Structured
15 PastPaper.marks
FastTrack Cargo is a regional logistics company with a central office and several remote distribution hubs. The company is upgrading its network infrastructure to allow remote drivers and warehouse staff to securely access the central inventory database.

(a) Explain the difference between a Local Area Network (LAN) and a Wide Area Network (WAN) in the context of FastTrack Cargo. [3]

(b) The company decides to implement a Virtual Private Network (VPN) for its remote workers. Explain two benefits of using a VPN for this purpose. [4]

(c) Explain how data packets are transmitted from a remote worker's device to the central database server using packet switching. [4]

(d) Outline the distinct roles of a router and a gateway in enabling this communication. [4]
PastPaper.showAnswers

PastPaper.workedSolution

(a)
- LAN: Operates within a limited geographical area, such as a single office or distribution hub of FastTrack Cargo. It is typically owned and managed directly by the company, offering high bandwidth and low latency.
- WAN: Extends over a large geographical distance to connect separate offices and distribution hubs. It relies on external telecommunications providers and public internet infrastructure, usually suffering from lower speeds and higher latency compared to a LAN.

(b)
- Benefit 1 (Data Encryption): A VPN encrypts all data sent between the remote drivers and the central office database. This ensures that even if packet data is intercepted on a public or insecure Wi-Fi network, it cannot be read or understood by unauthorized third parties.
- Benefit 2 (Secure Tunneling and Access Control): A VPN establishes a secure 'tunnel' that authenticates the user's credentials before granting entry. This acts as a gateway protection mechanism, preventing unauthorized entities from gaining direct access to the private network resources.

(c)
- Packetization: The message or query from the driver is split into smaller, manageable pieces called packets. Each packet contains a header with control info (such as source IP, destination IP, and packet sequence number) and the payload (data).
- Independent Routing: Each packet is sent out onto the internet where routers dynamically determine the optimal path. Packets may travel via different routes depending on current network congestion.
- Reassembly: Once the packets arrive at the central database server, they are reordered and reassembled into the original message using the sequence numbers in the headers.
- Error Checking: If any packet is detected as corrupted or is missing, the receiving server requests a retransmission of that specific packet.

(d)
- Router: Connects the LAN to the WAN. Its primary role is to inspect the destination IP address of incoming packets and use a routing table to forward those packets along the most efficient route toward their target.
- Gateway: Serves as the entry and exit point of a network and performs protocol translation. Because the internal network of FastTrack Cargo and the public internet might run on different communication protocol suites, the gateway translates these protocols to ensure seamless communication between disparate systems.

PastPaper.markingScheme

Total: 15 marks

(a) [3 marks]
- 1 mark: Defining LAN's limited geographical scope (e.g., single office, warehouse).
- 1 mark: Defining WAN's large geographical scope (e.g., connecting multiple cities/hubs).
- 1 mark: Highlighting a key structural/ownership difference (e.g., LAN uses local private wiring, WAN uses third-party telecommunication lines or public internet).

(b) [4 marks]
- Award 2 marks for each well-explained benefit:
- 1 mark for identifying the technical mechanism (e.g., encryption, IP spoofing prevention, tunneling).
- 1 mark for context-based explanation (e.g., preventing interception on public Wi-Fi, securing driver credentials).

(c) [4 marks]
- 1 mark: Explanation of packetization (splitting data into packets with headers/sequence numbers).
- 1 mark: Explanation of dynamic/independent routing of individual packets across various paths.
- 1 mark: Explanation of reassembly at the receiving node using sequence numbers.
- 1 mark: Explanation of error-checking / retransmission protocols.

(d) [4 marks]
- Router (Max 2 marks):
- 1 mark: Identifies that it routes packets across different networks.
- 1 mark: Explains that it uses routing tables and IP addresses to determine the next hop.
- Gateway (Max 2 marks):
- 1 mark: Identifies that it functions as a network interface converter/entry-exit node.
- 1 mark: Explains that it converts between different network protocols/formats.
PastPaper.question 2 · essay
15 PastPaper.marks
An automated climate control system in a smart greenhouse monitors three environmental sensors:
- \(T\) (Temperature high): 1 if temperature > 30°C, 0 otherwise.
- \(H\) (Humidity low): 1 if humidity < 40%, 0 otherwise.
- \(W\) (Water reservoir empty): 1 if water level is critically low, 0 otherwise.

The system controls two outputs:
- \(S\) (Sprinkler system): Activated (1) if the temperature is high AND the water reservoir is NOT empty.
- \(A\) (Emergency alarm): Activated (1) if the water reservoir is empty AND either the temperature is high OR the humidity is low (or both).

(a) Construct a complete truth table for the system showing all possible input combinations of \(T\), \(H\), and \(W\), and the corresponding outputs \(S\) and \(A\). [4 marks]

(b) (i) Write the Boolean expressions for both \(S\) and \(A\) using standard Boolean operators (AND, OR, NOT). [2 marks]
(ii) Describe how a logic circuit for output \(A\) can be constructed using standard logic gates. Specify the inputs and outputs for each gate. [2 marks]

(c) Write an algorithm in pseudocode that runs continuously to control this system. The algorithm must:
- Repeatedly read the sensor values every 10 seconds.
- Call a helper function `readSensors()` which returns an array of three integers `[T, H, W]` in that order (using 0-based indexing: `T` is index 0, `H` is index 1, `W` is index 2).
- Evaluate the logical conditions for \(S\) and \(A\).
- Control the physical components using the predefined sub procedures `turnSprinkler(status)` and `triggerAlarm(status)` where `status` is a boolean value (`true` or `false`).
- Use a built-in method `sleep(10)` to pause execution for 10 seconds in each loop cycle. [7 marks]
PastPaper.showAnswers

PastPaper.workedSolution

**(a) Truth Table**

| T | H | W | S | A |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 0 | 0 |
| 0 | 1 | 0 | 0 | 0 |
| 0 | 1 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 | 0 |
| 1 | 0 | 1 | 0 | 1 |
| 1 | 1 | 0 | 1 | 0 |
| 1 | 1 | 1 | 0 | 1 |

**(b) (i) Boolean Expressions**
- \(S = T \cdot \overline{W}\) (or \(S = T \text{ AND NOT } W\))
- \(A = W \cdot (T + H)\) (or \(A = W \text{ AND } (T \text{ OR } H)\))

**(b) (ii) Logic Circuit Connection Description**
1. Connect the sensor inputs \(T\) and \(H\) to the two inputs of an OR gate.
2. Connect the output of this OR gate and the sensor input \(W\) to the two inputs of an AND gate.
3. The output of this AND gate produces the final signal for output \(A\).

**(c) Pseudocode Implementation**
```
loop while true
sensorData = readSensors()
T = sensorData[0]
H = sensorData[1]
W = sensorData[2]

// Control Sprinkler System (S)
if T == 1 and W == 0 then
turnSprinkler(true)
else
turnSprinkler(false)
end if

// Control Emergency Alarm (A)
if W == 1 and (T == 1 or H == 1) then
triggerAlarm(true)
else
triggerAlarm(false)
end if

sleep(10)
end loop
```

PastPaper.markingScheme

**(a) [4 marks]**
- **1 mark** for correctly and systematically listing all 8 possible input combinations of \(T\), \(H\), and \(W\).
- **1.5 marks** for the correct output column for \(S\) (1 when \(T=1, W=0\); 0 otherwise). Deduct 0.5 marks per error up to 1.5.
- **1.5 marks** for the correct output column for \(A\) (1 when \(W=1\) and either \(T=1\) or \(H=1\); 0 otherwise). Deduct 0.5 marks per error up to 1.5.

**(b) (i) [2 marks]**
- **1 mark** for correct Boolean expression for \(S\).
- **1 mark** for correct Boolean expression for \(A\).

**(b) (ii) [2 marks]**
- **1 mark** for identifying the correct first stage: Passing \(T\) and \(H\) through an OR gate.
- **1 mark** for identifying the correct second stage: Passing the OR gate output and \(W\) through an AND gate to get \(A\).

**(c) [7 marks]**
- **1 mark** for constructing an infinite loop structure (e.g., `loop while true` or `loop forever`).
- **1 mark** for invoking `readSensors()` correctly and storing the returned array.
- **1 mark** for extracting values using correct indices (`sensorData[0]` for \(T\), `sensorData[1]` for \(H\), `sensorData[2]` for \(W\)).
- **1 mark** for correct evaluation of sprinkler condition and executing `turnSprinkler(true)` and `turnSprinkler(false)` based on outcomes.
- **2 marks** for correct evaluation of alarm condition and executing `triggerAlarm(true)` and `triggerAlarm(false)` based on outcomes (1 mark for logical structure, 1 mark for correct boolean operators/nesting).
- **1 mark** for including `sleep(10)` at the end of the loop body to ensure correct execution timing.
PastPaper.question 3 · Section B
15 PastPaper.marks
A school library manages its inventory using a collection of Book objects named libraryBooks. Each Book object provides the following methods:
- getTitle(): returns the string title of the book.
- getAuthor(): returns the string author of the book.
- getBorrowCount(): returns the integer number of times the book has been borrowed.

(a) Describe two differences between a Collection and an Array. [3]

(b) Construct an algorithm in pseudocode to find and output the title of the book with the highest borrow count. You should assume that the collection is not empty and that there is a unique maximum. [4]

(c) The librarian wants to sort the books in descending order of their borrow counts. Because a Collection cannot be easily sorted in-place, the librarian decides to copy all Book objects from the collection into an array named bookArray of size numBooks (where numBooks is an integer representing the total number of books), and then apply a sorting algorithm.

(i) Construct an algorithm in pseudocode to copy all elements from the libraryBooks collection into the array bookArray of size numBooks. [3]

(ii) Construct an algorithm in pseudocode to perform a Bubble Sort on bookArray to sort the books in descending order of their borrow counts. [5]
PastPaper.showAnswers

PastPaper.workedSolution

(a)
- Size: An array has a fixed size defined at the time of creation, whereas a collection is dynamic and can grow or shrink as elements are added or removed.
- Access: Array elements can be accessed directly using index notation (e.g. bookArray[i]), whereas collection elements must be accessed sequentially using an iterator (e.g. getNext()).
- Memory: Arrays occupy a contiguous block of memory, whereas collection elements may be stored in non-contiguous memory locations connected via pointers.

(b)
libraryBooks.resetNext()
maxBook = libraryBooks.getNext()
maxCount = maxBook.getBorrowCount()
while libraryBooks.hasNext()
currentBook = libraryBooks.getNext()
if currentBook.getBorrowCount() > maxCount then
maxBook = currentBook
maxCount = currentBook.getBorrowCount()
end if
end while
output maxBook.getTitle()

(c)(i)
libraryBooks.resetNext()
index = 0
while libraryBooks.hasNext()
bookArray[index] = libraryBooks.getNext()
index = index + 1
end while

(c)(ii)
loop i from 0 to numBooks - 2
loop j from 0 to numBooks - i - 2
if bookArray[j].getBorrowCount() < bookArray[j+1].getBorrowCount() then
temp = bookArray[j]
bookArray[j] = bookArray[j+1]
bookArray[j+1] = temp
end if
end loop
end loop

PastPaper.markingScheme

(a) Award 1 mark for each valid difference up to 3 marks.
- Array is static / has fixed size, while Collection is dynamic / size can change.
- Array elements are accessed directly via index (random access), while Collection elements are accessed sequentially via pointer/iterator.
- Array stores elements contiguously in memory, while Collection uses linked/non-contiguous structures.

(b) Award 4 marks as follows:
- 1 mark: Correctly resetting the collection and initializing tracking variables using the first element.
- 1 mark: Correctly implementing a loop using .hasNext().
- 1 mark: Correctly retrieving the next element using .getNext() and comparing its borrow count with the maximum.
- 1 mark: Correctly updating the maximum values and outputting the title of the book after the loop.

(c)(i) Award 3 marks as follows:
- 1 mark: Correctly resetting the collection and initializing index counter to 0.
- 1 mark: Correctly implementing the loop with .hasNext().
- 1 mark: Correctly assigning the book to bookArray at the index and incrementing the index.

(c)(ii) Award 5 marks as follows:
- 1 mark: Correctly implementing nested loops to traverse the array.
- 1 mark: Correctly setting inner loop boundaries to avoid index out of bounds (e.g., up to numBooks - i - 2).
- 1 mark: Correctly accessing and comparing the borrow count of adjacent elements using '<' (for descending order).
- 1 mark: Correctly swapping the elements using a temporary variable.
- 1 mark: Correctly indexing the array elements throughout the algorithm.

Paper 2 Option D (OOP)

Answer all questions from the option selected.
4 PastPaper.question · 45 PastPaper.marks
PastPaper.question 1 · Structured
14 PastPaper.marks
A fitness application uses Object-Oriented Programming (OOP) to track user activities.

The superclass Workout is defined with the following attributes and methods:
- Private String workoutID
- Private int duration (in minutes)
- Protected double baseMetabolicRate
- Constructor Workout(String workoutID, int duration, double baseMetabolicRate)
- Public accessor and mutator methods
- Public double calculateCalories() which returns duration * baseMetabolicRate

The subclass CardioWorkout inherits from Workout and has the following additional features:
- Private int avgHeartRate
- Constructor CardioWorkout(String workoutID, int duration, double baseMetabolicRate, int avgHeartRate)
- Public double calculateCalories() which overrides the superclass method to return duration * baseMetabolicRate * (avgHeartRate / 100.0)

(a) State the OOP relationship between Workout and CardioWorkout. [1 mark]

(b) Outline one advantage of using inheritance in this scenario. [2 marks]

(c) Construct the UML class diagram representation for the CardioWorkout class only. (Note: You do not need to draw the Workout class box, but you must specify all attributes, methods, visibility modifiers, and return types for CardioWorkout using correct UML notation). [4 marks]

(d) Write the Java code for the constructor of the Workout class. [3 marks]

(e) Write the Java code for the constructor of the CardioWorkout class. [4 marks]
PastPaper.showAnswers

PastPaper.workedSolution

(a)
Inheritance (or "is-a" relationship, where CardioWorkout is a subclass/child class of Workout).

(b)
Inheritance allows code reuse. Instead of re-declaring and re-implementing common attributes (such as workoutID, duration, and baseMetabolicRate) and their associated getters/setters in CardioWorkout, the subclass automatically inherits them from Workout. This reduces redundancy and simplifies future software maintenance.

(c)
UML Class Diagram for CardioWorkout:
-------------------------------------------------------
| CardioWorkout |
-------------------------------------------------------
| - avgHeartRate : int |
-------------------------------------------------------
| + CardioWorkout(workoutID: String, duration: int, |
| baseMetabolicRate: double, avgHeartRate: int) |
| + calculateCalories() : double |
-------------------------------------------------------

(d)
Java code for Workout constructor:
```java
public Workout(String workoutID, int duration, double baseMetabolicRate) {
this.workoutID = workoutID;
this.duration = duration;
this.baseMetabolicRate = baseMetabolicRate;
}
```

(e)
Java code for CardioWorkout constructor:
```java
public CardioWorkout(String workoutID, int duration, double baseMetabolicRate, int avgHeartRate) {
super(workoutID, duration, baseMetabolicRate);
this.avgHeartRate = avgHeartRate;
}
```

PastPaper.markingScheme

Part (a) [1 mark]
- Award 1 mark for stating "Inheritance" or "is-a relationship".

Part (b) [2 marks]
- Award 1 mark for identifying a valid advantage (e.g., code reuse, reduced redundancy, easier maintenance).
- Award 1 mark for linking the advantage specifically to the scenario (e.g., inheriting workoutID/duration/baseMetabolicRate from Workout).

Part (c) [4 marks]
- Award 1 mark for the correct class name CardioWorkout and the attribute "- avgHeartRate : int" (must use '-' for private and correct colon-type notation).
- Award 1 mark for the constructor shown with '+' public visibility, all 4 parameters, and correct types.
- Award 1 mark for the overridden method "+ calculateCalories() : double" with '+' visibility and correct return type.
- Award 1 mark for applying correct UML syntax throughout (no Java syntax for declarations, correct use of ':' for types).

Part (d) [3 marks]
- Award 1 mark for the correct constructor signature: public Workout(String workoutID, int duration, double baseMetabolicRate).
- Award 1 mark for using 'this' keyword (or alternative distinct naming parameters) to resolve shadowing/ambiguity.
- Award 1 mark for assigning all three local parameters to their corresponding instance fields.

Part (e) [4 marks]
- Award 1 mark for the correct constructor signature with all 4 arguments: public CardioWorkout(String workoutID, int duration, double baseMetabolicRate, int avgHeartRate).
- Award 1 mark for using the correct "super(...)" keyword calling the superclass constructor.
- Award 1 mark for passing the correct parameters (workoutID, duration, baseMetabolicRate) to "super()" as the very first line of the constructor.
- Award 1 mark for correctly assigning "this.avgHeartRate = avgHeartRate;".
PastPaper.question 2 · Structured
8 PastPaper.marks
An eco-friendly navigation system, 'EcoRoute', is being developed. The application is planned to have several modules, including a path-finding engine, a user interface, and an external weather API connector. The system design includes classes such as Route, Vehicle, GPSCoordinate, and TrafficSensor.

(a) Explain two benefits of modularity during the development phase of the EcoRoute application. [4]

(b) In the design, a Route object is composed of multiple GPSCoordinate objects. A Vehicle object temporarily accesses a TrafficSensor object to retrieve real-time congestion updates, but does not store a reference to it. Outline the OOP relationships described here and explain how they differ. [4]
PastPaper.showAnswers

PastPaper.workedSolution

(a) Benefits of Modularity in development:
- **Division of Labor / Parallel Development**: Different programmers or development teams can work on different modules simultaneously. For example, one team can develop the complex path-finding engine while another designs the user interface module. This significantly speeds up the development process.
- **Reusability**: Once a module is developed and tested, it can be reused in other parts of the application or future projects. For instance, the external weather API connector module can be reused in a different meteorological app without rewriting the communication code.
- **Easier Debugging and Maintenance**: Since the system is divided into self-contained units, errors can be isolated quickly. If the system fails to display weather updates, developers can focus troubleshooting exclusively on the weather API module without searching through the entire codebase.

(b) OOP Relationships and Differences:
- **Route and GPSCoordinate**: This is an **Aggregation** (or Composition) relationship. It represents a "has-a" association where a Route acts as a container/whole and GPSCoordinates act as the components/parts. This relationship is structural and persistent; the Route maintains long-term references to its coordinates.
- **Vehicle and TrafficSensor**: This is a **Dependency** relationship. It represents a "uses-a" association where the Vehicle temporarily relies on the TrafficSensor to execute a specific task (e.g., retrieving an update passing through a method parameter), but does not own or maintain a long-term reference to it.
- **Difference**: Aggregation is a stronger, structural relationship where one object structurally contains others as part of its state. Dependency is a weaker, transient association where one class merely utilizes the services of another temporarily, resulting in lower coupling between the two classes.

PastPaper.markingScheme

Part (a) [4 marks]
- Award [1 mark] for identifying a valid benefit of modularity (up to 2 benefits).
- Award [1 mark] for explaining each benefit in the context of the EcoRoute application (up to 2 benefits).
- *Example benefits*: Division of labor, reusability of modules, ease of debugging/maintenance, encapsulation of changes.

Part (b) [4 marks]
- Award [1 mark] for correctly identifying the Route-GPSCoordinate relationship as Aggregation (or Composition/"has-a").
- Award [1 mark] for describing how Route contains GPSCoordinate structurally.
- Award [1 mark] for correctly identifying the Vehicle-TrafficSensor relationship as Dependency (or "uses-a").
- Award [1 mark] for explaining the difference (e.g., aggregation is persistent/structural containment, while dependency is transient/use-only, leading to looser coupling).
PastPaper.question 3 · practical
15 PastPaper.marks
An athletics club uses an object-oriented program to manage race participants.

The Participant class is defined as follows:
class Participant {
private String name;
private String category; // e.g., "Under-18", "Senior", "Master"
private int runningTime; // finishing time in seconds

// Constructor and methods
}
The Race class contains an array of Participant objects:
class Race {
private Participant[] runners;
private int count; // actual number of runners in the array

// Constructor and methods
}
Assume that the Participant class has standard accessor (getter) methods: getName(), getCategory(), and getRunningTime().

(a) Outline the purpose of a constructor in object-oriented programming. [2 marks]

(b) Construct the constructor for the Participant class, which initializes all three instance variables using parameters. [3 marks]

(c) Construct the method getGoldMedalist(String targetCategory) in the Race class. This method must search through the first count elements of the runners array and return the Participant object with the lowest runningTime that matches the targetCategory. If no runner matches the category or if the list is empty, the method should return null. [10 marks]
PastPaper.showAnswers

PastPaper.workedSolution

(a)
The purpose of a constructor is to initialize the instance variables (state) of an object when it is created/instantiated. It is automatically called when the new operator is used.

(b)
public Participant(String name, String category, int runningTime) {
this.name = name;
this.category = category;
this.runningTime = runningTime;
}

(c)
public Participant getGoldMedalist(String targetCategory) {
Participant goldMedalist = null;
int bestTime = Integer.MAX_VALUE;

for (int i = 0; i < count; i++) {
if (runners[i] != null) {
if (runners[i].getCategory().equals(targetCategory)) {
if (runners[i].getRunningTime() < bestTime) {
bestTime = runners[i].getRunningTime();
goldMedalist = runners[i];
}
}
}
}
return goldMedalist;
}

PastPaper.markingScheme

(a) [2 marks]
Award 1 mark for stating that it initializes instance variables/state.
Award 1 mark for stating that it runs automatically during instantiation / when using the new keyword.

(b) [3 marks]
Award 1 mark for correct method header (matches class name exactly, includes matching arguments: String, String, int).
Award 1 mark for correct assignments (e.g., this.name = name; or equivalent).
Award 1 mark for correct overall Java syntax (no return type specified).

(c) [10 marks]
Award 1 mark for correct method header: public Participant getGoldMedalist(String targetCategory).
Award 1 mark for declaring and initializing a tracker variable for the minimum/best time (e.g., to a very high value like Integer.MAX_VALUE).
Award 1 mark for declaring and initializing a Participant reference to null (to track the gold medalist).
Award 1 mark for writing a loop that correctly iterates up to count elements.
Award 1 mark for checking that the current array element runners[i] is not null to prevent NullPointerException.
Award 1 mark for calling getCategory() correctly on the runner object.
Award 1 mark for using .equals() to compare String category values (do not accept == for string comparison).
Award 1 mark for comparing the current runner's time (retrieved via getRunningTime()) to the current best time.
Award 1 mark for updating the tracker variables (both the minimum time and the Participant reference) inside the conditional block.
Award 1 mark for returning the tracked Participant reference at the end of the method.
PastPaper.question 4 · essay
8 PastPaper.marks
A software development team is designing an Object-Oriented software system for a clinic. They have identified three classes:
- `Patient`: Represents a clinic patient.
- `MedicalRecord`: Represents a patient's historical medical data.
- `DatabaseConnector`: Handles connection and raw data transmission to the clinic's external server.

(a) Describe the differences between the **aggregation** relationship (as seen between `Patient` and `MedicalRecord`) and the **dependency** relationship (as seen between `Patient` and `DatabaseConnector`). [4]

(b) Explain one ethical or security concern regarding data privacy if the `Patient` class directly transmits unencrypted patient data through the `DatabaseConnector`, and outline how the object-oriented design can be modified to address this issue. [4]
PastPaper.showAnswers

PastPaper.workedSolution

**Part (a)**
- **Aggregation ('has-a')**: This is a specialized, association-based relationship where one class is a container of another. Here, a `Patient` object has a `MedicalRecord` object. They have a lifetime relationship, but the `MedicalRecord` can exist independently of the `Patient` (e.g., if the patient leaves the clinic, the record remains in the archive).
- **Dependency ('uses')**: This is a weaker, temporary relationship where a change in one class (`DatabaseConnector`) can affect another class (`Patient`). The `Patient` class does not maintain a persistent instance of `DatabaseConnector` as an attribute; rather, it temporarily 'uses' it (for instance, invoking a static method or instantiating it locally inside a `save()` method) to perform an operation.

**Part (b)**
- **Ethical/Security Concern**: Patient health data is highly sensitive. Transmitting unencrypted data directly creates a vulnerability to packet sniffing or unauthorized data interception, which violates the ethical principle of patient-doctor confidentiality and legal frameworks (e.g., HIPAA/GDPR).
- **Design Modification**: Implement the **Principle of Least Privilege** or **Encapsulation** by introducing an intermediary security wrapper or helper class (e.g., `SecureDataEncryptor`). The `Patient` class passes data to `SecureDataEncryptor` first, which outputs ciphertext. The `DatabaseConnector` is then only allowed to receive and transmit this encrypted data, preventing raw medical information from being exposed within the communication subsystem.

PastPaper.markingScheme

**Part (a) [4 marks]**
- **[1 mark]** For defining/describing **Aggregation** as a 'has-a' / whole-part relationship.
- **[1 mark]** For explaining that aggregated objects have independent lifetimes (e.g., `MedicalRecord` can exist without `Patient`).
- **[1 mark]** For defining/describing **Dependency** as a 'uses' relationship where one class depends on the definition of another.
- **[1 mark]** For explaining the temporary nature of dependency in code (e.g., `DatabaseConnector` is only used inside a method scope/parameter, not stored as an instance field).

**Part (b) [4 marks]**
- **[1 mark]** For identifying a valid ethical concern (e.g., violation of patient confidentiality, breach of data protection laws).
- **[1 mark]** For explaining *how* the direct transmission of unencrypted data by `Patient` leads to this concern (e.g., interception by third parties, exposure of raw medical diagnostics).
- **[1 mark]** For proposing a valid OO design change (e.g., adding an intermediary encryption class, wrapper class, or using private encapsulation access modifiers).
- **[1 mark]** For explaining how this change resolves the issue (e.g., ensures `DatabaseConnector` only handles encrypted ciphertext, isolating sensitive data exposure).

PastPaper.sampleCTATitle

PastPaper.sampleCTADescription

PastPaper.sampleStickyMessage

PastPaper.stickyCtaText