IB DP · Thinka-original Practice Paper

2025 IB DP Computer Science Practice Paper with Answers

Thinka May 2025 SL (TZ3) IB Diploma Programme-Style Mock — Computer Science

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

Paper 1 Section A

Answer all questions. Calculators are not permitted.
8 Question · 27 marks
Question 1 · short-answer
2.5 marks
A retail company is moving from an older legacy desktop database to a modern cloud-based inventory system. Describe one advantage and one disadvantage of using a phased introduction compared to a direct changeover.
Show answer & marking scheme

Worked solution

A phased introduction allows the organization to implement the new system in stages (e.g., department by department). If an issue occurs, it is isolated to that specific phase, reducing risk. However, it requires running both systems in parallel for different business functions, which leads to double data entry, potential compatibility issues, and prolonged training times.

Marking scheme

[1 mark] for a valid advantage of a phased changeover (e.g., lower risk, easier staff training). [1 mark] for a valid disadvantage (e.g., compatibility issues, high cost of running two systems). [0.5 marks] for explicit comparison/link to direct changeover.
Question 2 · short-answer
2.5 marks
Explain how the use of cache memory speeds up the instruction cycle (fetch-execute cycle) inside a central processing unit (CPU).
Show answer & marking scheme

Worked solution

Cache memory is extremely fast, high-speed SRAM located on or very close to the CPU core. It holds copies of frequently or recently used instructions and data. During the fetch stage of the cycle, the CPU checks the cache first. If a cache hit occurs, the instruction is loaded immediately, avoiding the latency associated with fetching data from the main system memory (RAM).

Marking scheme

[1 mark] for identifying cache as faster memory storing frequently accessed data/instructions. [1 mark] for explaining the process of checking cache first (cache hit vs cache miss). [0.5 marks] for linking this directly to the reduction of CPU idle time during the fetch phase.
Question 3 · short-answer
2.5 marks
In packet-switched networks, explain why packets may arrive at their destination out of order and how this issue is resolved at the destination.
Show answer & marking scheme

Worked solution

Each packet in a packet-switched network is routed independently. Because network congestion and route availability change dynamically, different packets of the same message may take different paths, resulting in varying transit times and out-of-order arrival. The destination host resolves this by inspecting the sequence numbers in the packet headers (such as TCP headers) and reordering them before delivering the complete message to the application layer.

Marking scheme

[1 mark] for explaining why packets arrive out of order (independent routing, dynamic paths, dynamic network congestion). [1 mark] for identifying the use of sequence numbers in packet headers. [0.5 marks] for explaining that the destination reassembles/reorders the packets based on these sequence numbers.
Question 4 · short-answer
2.5 marks
Consider a sorted array of 1,000 unique integers. Calculate the maximum number of comparisons required to search for a specific target value using a binary search algorithm. Show your working.
Show answer & marking scheme

Worked solution

Binary search continually halves the search space. The maximum number of comparisons is given by \(\lceil \log_2(N+1) \rceil\) or \(\lfloor \log_2(N) \rfloor + 1\). For \(N = 1000\): \(2^9 = 512\) and \(2^{10} = 1024\). Since \(512 < 1000 \le 1024\), it will take a maximum of 10 comparisons to either find the item or determine that it is not present.

Marking scheme

[1 mark] for identifying the binary division relationship (halving the search space) or writing the logarithmic formula. [1 mark] for showing correct calculation steps (e.g., matching \(2^{10} = 1024\)). [0.5 marks] for the final correct answer of 10.
Question 5 · short-answer
2.5 marks
Identify two distinct accessibility features that can be integrated into an operating system user interface to assist users with visual impairments, and explain how each feature improves usability.
Show answer & marking scheme

Worked solution

Two features are: 1. Screen readers: These use text-to-speech engines to read out text, menus, and image descriptions, allowing blind users to navigate the system using audio cues. 2. High-contrast themes / adjustable text size: These modify the visual representation to make elements stand out clearly, assisting users with low vision or color blindness to read text and identify UI elements easily.

Marking scheme

[1 mark] for identifying two valid OS-level accessibility features (0.5 marks each). [1 mark] for explaining how each feature improves usability (0.5 marks each). [0.5 marks] for linking both explanations directly to visual impairment needs.
Question 6 · short-answer
2.5 marks
Consider the following algorithm: A = 12; B = 18; while B != 0: T = B; B = A mod B; A = T; end while; output A. Construct a trace table to determine the final output of the algorithm.
Show answer & marking scheme

Worked solution

Let's trace the values: Initially: A = 12, B = 18. Iteration 1: B is not 0 (18 != 0). T = 18. B = 12 mod 18 = 12. A = 18. Iteration 2: B is not 0 (12 != 0). T = 12. B = 18 mod 12 = 6. A = 12. Iteration 3: B is not 0 (6 != 0). T = 6. B = 12 mod 6 = 0. A = 6. Iteration 4: B is 0. The loop terminates. Output A is 6. This is the Euclidean algorithm for finding the greatest common divisor (GCD).

Marking scheme

[1 mark] for showing correct values after the first loop iteration (A = 18, B = 12). [1 mark] for showing correct subsequent transitions (A = 12, B = 6 then A = 6, B = 0). [0.5 marks] for the correct final output of 6.
Question 7 · trace-table
6 marks
An algorithm is represented by the following pseudocode:

NUMS = [4, 7, 3, 6, 2]
A = 0
B = 10
I = 0
loop while I < 5
X = NUMS[I]
if X mod 2 == 0 then
A = A + X
B = B - 1
else
A = A - X
B = B + 2
end if
I = I + 1
end loop

Copy and complete the trace table below to show the execution of this algorithm.

| I | X | A | B |
|---|---|---|---|
| 0 | | 0 | 10|
| | | | |
Show answer & marking scheme

Worked solution

The execution of the algorithm step-by-step is as follows:
- **Initial State**: I = 0, A = 0, B = 10.
- **First Iteration (I = 0)**: X is assigned NUMS[0] which is 4. Since 4 mod 2 == 0, A becomes A + 4 = 4, and B becomes B - 1 = 9. I is incremented to 1.
- **Second Iteration (I = 1)**: X is assigned NUMS[1] which is 7. Since 7 mod 2 != 0, A becomes A - 7 = -3, and B becomes B + 2 = 11. I is incremented to 2.
- **Third Iteration (I = 2)**: X is assigned NUMS[2] which is 3. Since 3 mod 2 != 0, A becomes A - 3 = -6, and B becomes B + 2 = 13. I is incremented to 3.
- **Fourth Iteration (I = 3)**: X is assigned NUMS[3] which is 6. Since 6 mod 2 == 0, A becomes A + 6 = 0, and B becomes B - 1 = 12. I is incremented to 4.
- **Fifth Iteration (I = 4)**: X is assigned NUMS[4] which is 2. Since 2 mod 2 == 0, A becomes A + 2 = 2, and B becomes B - 1 = 11. I is incremented to 5.
- **Loop Termination**: I is now 5, the loop condition (I < 5) evaluates to False, and the loop terminates.

Completed Trace Table:
| I | X | A | B |
|---|---|---|---|
| 0 | | 0 | 10|
| 1 | 4 | 4 | 9 |
| 2 | 7 | -3| 11|
| 3 | 3 | -6| 13|
| 4 | 6 | 0 | 12|
| 5 | 2 | 2 | 11|

Marking scheme

Award [1 mark] for each correct row of the trace table up to a maximum of [6 marks]:
- [1 mark] for initial values correct (I=0, A=0, B=10).
- [1 mark] for Row 1 (I=1, X=4, A=4, B=9) correct.
- [1 mark] for Row 2 (I=2, X=7, A=-3, B=11) correct.
- [1 mark] for Row 3 (I=3, X=3, A=-6, B=13) correct.
- [1 mark] for Row 4 (I=4, X=6, A=0, B=12) correct.
- [1 mark] for Row 5 (I=5, X=2, A=2, B=11) correct.
Question 8 · trace-table
6 marks
An algorithm is represented by the following pseudocode:

NUMS = [4, 7, 3, 6, 2]
A = 0
B = 10
I = 0
loop while I < 5
X = NUMS[I]
if X mod 2 == 0 then
A = A + X
B = B - 1
else
A = A - X
B = B + 2
end if
I = I + 1
end loop

Copy and complete the trace table below to show the execution of this algorithm.

| I | X | A | B |
|---|---|---|---|
| 0 | | 0 | 10|
| | | | |
Show answer & marking scheme

Worked solution

The execution of the algorithm step-by-step is as follows:
- **Initial State**: I = 0, A = 0, B = 10.
- **First Iteration (I = 0)**: X is assigned NUMS[0] which is 4. Since 4 mod 2 == 0, A becomes A + 4 = 4, and B becomes B - 1 = 9. I is incremented to 1.
- **Second Iteration (I = 1)**: X is assigned NUMS[1] which is 7. Since 7 mod 2 != 0, A becomes A - 7 = -3, and B becomes B + 2 = 11. I is incremented to 2.
- **Third Iteration (I = 2)**: X is assigned NUMS[2] which is 3. Since 3 mod 2 != 0, A becomes A - 3 = -6, and B becomes B + 2 = 13. I is incremented to 3.
- **Fourth Iteration (I = 3)**: X is assigned NUMS[3] which is 6. Since 6 mod 2 == 0, A becomes A + 6 = 0, and B becomes B - 1 = 12. I is incremented to 4.
- **Fifth Iteration (I = 4)**: X is assigned NUMS[4] which is 2. Since 2 mod 2 == 0, A becomes A + 2 = 2, and B becomes B - 1 = 11. I is incremented to 5.
- **Loop Termination**: I is now 5, the loop condition (I < 5) evaluates to False, and the loop terminates.

Completed Trace Table:
| I | X | A | B |
|---|---|---|---|
| 0 | | 0 | 10|
| 1 | 4 | 4 | 9 |
| 2 | 7 | -3| 11|
| 3 | 3 | -6| 13|
| 4 | 6 | 0 | 12|
| 5 | 2 | 2 | 11|

Marking scheme

Award [1 mark] for each correct row of the trace table up to a maximum of [6 marks]:
- [1 mark] for initial values correct (I=0, A=0, B=10).
- [1 mark] for Row 1 (I=1, X=4, A=4, B=9) correct.
- [1 mark] for Row 2 (I=2, X=7, A=-3, B=11) correct.
- [1 mark] for Row 3 (I=3, X=3, A=-6, B=13) correct.
- [1 mark] for Row 4 (I=4, X=6, A=0, B=12) correct.
- [1 mark] for Row 5 (I=5, X=2, A=2, B=11) correct.

Paper 1 Section B

Answer all questions. Each question is based on a real-world scenario.
3 Question · 45 marks
Question 1 · structured-scenario
15 marks
A medical clinic currently uses a paper-based patient booking and records system. They plan to upgrade to a modern cloud-based Electronic Health Record (EHR) system.

(a) Identify two stakeholders who should be consulted during the planning stage of this system upgrade. [2]

(b) Describe one method of obtaining requirements from these stakeholders and explain one advantage of this method. [3]

(c) The clinic is considering two implementation methods: direct changeover and parallel running.
(i) Compare these two methods in terms of risk and cost. [4]
(ii) Recommend, with a reason, which implementation method the clinic should use. [2]

(d) Explain the importance of data migration in this project and identify two problems that may arise during the data migration process. [4]
Show answer & marking scheme

Worked solution

(a) Two stakeholders to consult:
- Medical staff (doctors, nurses)
- Administrative/receptionist staff
- Clinic management/directors
- Patients (limited consultation/feedback)

(b) Requirements gathering method and advantage:
- Method: Interviews (e.g., face-to-face discussions with doctors and administrators to understand their workflow).
- Advantage: Allows for deep qualitative insights, clarification of complex medical procedures, and follow-up questions to uncover non-obvious requirements.
- Alternative Method: Direct observation (observing receptionists checking in patients).
- Alternative Advantage: Provides objective, first-hand data on how things are actually done rather than what users say they do.

(c) (i) Comparison of implementation methods:
- Direct changeover: Low cost because only one system is run at a time (no double entry or running redundant servers), but high risk because if the new system fails, there is no backup system to rely on, which could halt clinic operations.
- Parallel running: High cost because both the legacy paper system and the new electronic system run simultaneously (requiring double input and extra workload), but low risk because if the new system fails, the clinic can immediately fall back on the paper system.

(c) (ii) Recommendation:
- Parallel running is highly recommended. Patient medical records are safety-critical. A direct changeover carries too much risk; a system failure could lead to lost patient data or an inability to access historical records during a medical emergency.

(d) Importance and problems of data migration:
- Importance: Ensure historical medical histories, patient contact info, and billing details are accurately transferred to the new database, preserving the continuity of patient care without starting from scratch.
- Problems (choose two):
1. Data format incompatibility: The old paper records or simple spreadsheets may not map directly to the structured schema of the new cloud EHR database.
2. Incomplete or duplicate data: Existing patient records might contain typos, missing fields, or redundant files, which will populate the new database with corrupt/invalid data ("garbage in, garbage out").
3. Data loss during migration: Network dropouts or transfer errors might lead to missing patient records.

Marking scheme

(a) [2 marks]
- Award 1 mark for each valid stakeholder identified, up to 2 marks.
- Accept: doctors, nurses, administrative staff, receptionists, IT technicians, clinic managers, patients.
- Reject: general public, competitors.

(b) [3 marks]
- Award 1 mark for identifying and describing a valid requirements gathering method.
- Award up to 2 marks for a well-explained advantage relevant to the method described.
- Acceptable methods: Interviews, questionnaires/surveys, direct observation, document analysis.

(c) (i) [4 marks]
- Award 1 mark for analyzing the risk of direct changeover (high risk explained).
- Award 1 mark for analyzing the cost of direct changeover (low cost explained).
- Award 1 mark for analyzing the risk of parallel running (low risk explained).
- Award 1 mark for analyzing the cost of parallel running (high cost explained).

(c) (ii) [2 marks]
- Award 1 mark for recommending parallel running.
- Award 1 mark for a justified reason linked to patient safety, data integrity, or system downtime.
- Note: Accept direct changeover only if accompanied by an exceptional justification (e.g., strict budget limits with intensive dry-run testing beforehand).

(d) [4 marks]
- Award up to 2 marks for explaining the importance of data migration (1 mark for continuity of care/retaining records, 1 mark for preventing data loss or downtime during transition).
- Award 1 mark each for identifying any two valid problems (up to 2 marks).
Question 2 · structured-scenario
15 marks
A large retail warehouse uses autonomous guided vehicles (AGVs) that communicate over a local wireless local area network (WLAN) to receive instructions from a central coordination server.

(a) Define the term *protocol* in the context of network communication and explain why standard protocols are necessary for this warehouse system. [3]

(b) The AGVs use packet switching to transmit telemetry data back to the server.
(i) Explain how telemetry data is prepared and transmitted using packet switching. [4]
(ii) Outline why packet switching is more efficient than circuit switching for this environment. [2]

(c) Explain how a firewall and data encryption could be used to secure the communication between the AGVs and the central coordination server. [4]

(d) State two factors that could cause interference or reduce the speed of the wireless network in a busy warehouse environment. [2]
Show answer & marking scheme

Worked solution

(a) Definition and necessity of protocol:
- Definition: A protocol is a set of rules and standards that govern how data is formatted, transmitted, and received across a network.
- Necessity: Standard protocols ensure interoperability. This allows AGVs made by different manufacturers, the server, and network routers to exchange data seamlessly regardless of their underlying hardware or operating systems.

(b) (i) Telemetry transmission via packet switching:
- The telemetry data is divided into smaller, manageable chunks called packets.
- Each packet is appended with a header containing routing details (sender/receiver IP addresses) and packet sequence numbers.
- Each packet is routed independently across the network based on the most efficient path available.
- Once all packets arrive at the destination server, they are reordered and reassembled into the original telemetry dataset using the sequence numbers.

(b) (ii) Packet switching vs. circuit switching:
- Packet switching is more efficient because AGVs send data in short, bursty intervals (telemetry/coordinates). Circuit switching would require a dedicated, continuous link to be reserved for each AGV, which would waste bandwidth when the AGV is idle. Packet switching allows multiple AGVs to dynamically share the same physical channel.

(c) Securing communication:
- Firewall: A firewall is placed at the entry/exit points of the network. It inspects incoming and outgoing traffic, filtering out unauthorized connection attempts from external devices trying to access the server or AGV network.
- Encryption: All transmitted instructions and telemetry data are scrambled into ciphertext using a strong algorithm. If malicious users intercept the wireless transmission, they will see only garbled data and will be unable to read or tamper with the instructions without the private decryption key.

(d) Wireless interference factors (choose two):
- Physical barriers (e.g., tall metal shelving units, concrete walls) causing signal attenuation.
- Electromagnetic radiation/interference from high-power electric motors or conveyor belts in the warehouse.
- Co-channel interference from other wireless devices (e.g., handheld inventory scanners, employee smartphones) operating on the same frequency band.

Marking scheme

(a) [3 marks]
- Award 1 mark for a precise definition of a protocol.
- Award up to 2 marks for a clear explanation of its necessity (focusing on interoperability/compatibility and standard rules of communication).

(b) (i) [4 marks]
- Award 1 mark for data segmentation into packets.
- Award 1 mark for adding header information (IP addresses, sequence numbers).
- Award 1 mark for packets being routed independently through the network.
- Award 1 mark for reassembling packets in the correct order at the destination.

(b) (ii) [2 marks]
- Award 1 mark for stating that AGV transmissions are bursty/non-continuous.
- Award 1 mark for explaining that circuit switching wastes dedicated bandwidth, whereas packet switching shares channel capacity dynamically.

(c) [4 marks]
- Award 1 mark for defining/explaining how a firewall operates (monitoring and filtering packet traffic).
- Award 1 mark for applying it to the scenario (preventing unauthorized external connections to AGVs/server).
- Award 1 mark for defining/explaining encryption (scrambling data into ciphertext).
- Award 1 mark for applying it to the scenario (preventing data theft or command spoofing if wireless packets are intercepted).

(d) [2 marks]
- Award 1 mark per valid physical or electromagnetic factor identified, up to 2 marks.
- Accept: metal shelving/structures, electromagnetic interference from heavy machinery, congestion from other devices, or competing WiFi signals.
Question 3 · pseudocode-construction
15 marks
An automated logistics distribution centre manages packages using three parallel arrays of size 500:

* `IDS`: an array of integers representing unique package identifiers.
* `DESTINATIONS`: an array of strings representing the destination cities of the packages.
* `WEIGHTS`: an array of real numbers representing the weights of the packages in kilograms.

(a) Define the term 'parallel arrays' and outline one disadvantage of using parallel arrays compared to an array of records/objects in this scenario. [3 marks]

(b) Construct an algorithm in pseudocode that accepts a target destination and the three arrays as parameters. The algorithm must process the arrays to:
- Calculate and output the total weight of all packages heading to the target destination.
- Find and output the ID of the heaviest package heading to that destination.
- Count and output how many packages heading to that destination weigh less than 5.0 kg.
- Output an appropriate error message if no packages are found matching the target destination.
[9 marks]

(c) Suggest, with a reason, how the efficiency of searching for a specific package ID could be improved if the `IDS` array were sorted in ascending order. Explain why this improvement introduces additional overhead in the parallel arrays scenario. [3 marks]
Show answer & marking scheme

Worked solution

### Part (a) Solution
Parallel arrays are two or more arrays of the same size where elements at the same index are logically related to each other (i.e., they represent different attributes of the same entity, such as `IDS[i]`, `DESTINATIONS[i]`, and `WEIGHTS[i]` describing the same package).

A key disadvantage of using parallel arrays compared to an array of objects is data integrity maintenance during sorting, deletion, or insertion. If you need to reorder or sort the data (e.g., sorting packages by weight), every array must be reordered in the exact same sequence. If one array is modified without identical changes to the others, the data relationship is permanently lost/corrupted. An array of objects binds all properties together natively, avoiding this risk.

### Part (b) Pseudocode Solution

```
processPackages(targetDest, IDS, DESTINATIONS, WEIGHTS)
totalWeight = 0.0
maxWeight = -1.0
heaviestID = -1
underFiveCount = 0
found = false

loop I from 0 to 499
if DESTINATIONS[I] == targetDest then
found = true
totalWeight = totalWeight + WEIGHTS[I]

if WEIGHTS[I] > maxWeight then
maxWeight = WEIGHTS[I]
heaviestID = IDS[I]
end if

if WEIGHTS[I] < 5.0 then
underFiveCount = underFiveCount + 1
end if
end if
end loop

if found == true then
output "Total Weight: ", totalWeight
output "Heaviest Package ID: ", heaviestID
output "Packages under 5kg: ", underFiveCount
else
output "No packages found for destination: ", targetDest
end if
end processPackages
```

### Part (c) Solution
- **Improvement:** By sorting the `IDS` array, we can use a Binary Search algorithm instead of a Linear Search.
- **Reason:** This improves search time complexity from \(O(N)\) to \(O(\log N)\), making searches significantly faster as the dataset scales.
- **Overhead:** Sorting the `IDS` array requires simultaneously reordering the corresponding elements in both the `DESTINATIONS` and `WEIGHTS` arrays to maintain index-level alignment. This parallel movement of data introduces significant computational overhead whenever a package is added, removed, or sorted.

Marking scheme

### Part (a) [3 marks]
- **1 mark:** Correct definition of 'parallel arrays' as multiple arrays where elements at the same index index correspond to the same real-world entity.
- **1 mark:** Identifying a valid disadvantage (e.g., maintaining alignment during operations like sorting, insertion, or deletion).
- **1 mark:** Developing the explanation contextually (e.g., sorting package IDs requires manually shifting destinations and weights; failure to do so results in mismatched package information).

### Part (b) [9 marks]
- **1 mark:** Initializing all tracking variables correctly (e.g., `totalWeight` to 0, `maxWeight` to a low/sentinel value, `found` to false).
- **1 mark:** Loop correctly configured to iterate through all 500 elements (e.g., `0 to 499` or `1 to 500` depending on index convention).
- **1 mark:** Correct conditional check comparing array elements to `targetDest` (e.g., `DESTINATIONS[I] == targetDest`).
- **1 mark:** Correct accumulation of `totalWeight` within the matching block.
- **2 marks:** Correct logic to determine the heaviest package (1 mark for updating the running maximum weight, 1 mark for storing the corresponding ID from the parallel array `IDS[I]`).
- **1 mark:** Correct counter increment for packages weighing under 5.0 kg.
- **1 mark:** Implementing a mechanism (such as a boolean flag or checking counter/total) to verify if any matches were found.
- **1 mark:** Correct final output of calculated values and appropriate error message handling when no matches are found.

### Part (c) [3 marks]
- **1 mark:** Suggesting Binary Search (or logarithmic search).
- **1 mark:** Explaining that it reduces the search time complexity to \(O(\log N)\), which is faster than \(O(N)\) linear search.
- **1 mark:** Explaining the overhead constraint: any sort of `IDS` requires the system to mirror every swap operation across both `DESTINATIONS` and `WEIGHTS` to prevent data corruption.

Paper 2 Option D (OOP)

Answer all questions in Option D.
3 Question · 45 marks
Question 1 · oop-class-design
15 marks
A health and fitness company is developing an application to track users' physical activities. The system uses object-oriented programming to represent different types of workouts. The base class is Workout, which stores general information about any physical activity. A subclass CardioWorkout represents workouts like running or cycling, which track additional metrics such as heart rate and distance.

(a) Explain the concept of encapsulation and describe how it would be applied to the design of the Workout class. [3 marks]

(b) Construct the complete Java class definition for the Workout class. The class should contain:
- Private attributes: workoutID (String), duration (integer in minutes), and caloriesBurned (double).
- A constructor that initializes all three attributes.
- Accessor (getter) methods for all three attributes.
- A method calculateIntensity() which, in this base class, simply returns the String "General". [5 marks]

(c) Construct the complete Java class definition for the subclass CardioWorkout. This class must:
- Inherit from the Workout class.
- Have additional private attributes: averageHeartRate (integer) and distance (double).
- Contain a constructor that accepts five parameters to initialize both the superclass and subclass attributes.
- Override the calculateIntensity() method to return:
* "High" if averageHeartRate is greater than 150.
* "Medium" if averageHeartRate is between 110 and 150 inclusive.
* "Low" if averageHeartRate is less than 110. [7 marks]
Show answer & marking scheme

Worked solution

(a) Encapsulation is the practice of bundling data (attributes) and methods that operate on that data into a single unit (class) while restricting direct access to the data from outside the class. In the Workout class, encapsulation is applied by declaring the attributes workoutID, duration, and caloriesBurned as private. These can only be read through public getter methods, preventing accidental or unauthorized alteration of raw data.

(b) Java Class Definition for Workout:

public class Workout {
private String workoutID;
private int duration;
private double caloriesBurned;

public Workout(String workoutID, int duration, double caloriesBurned) {
this.workoutID = workoutID;
this.duration = duration;
this.caloriesBurned = caloriesBurned;
}

public String getWorkoutID() {
return this.workoutID;
}

public int getDuration() {
return this.duration;
}

public double getCaloriesBurned() {
return this.caloriesBurned;
}

public String calculateIntensity() {
return "General";
}
}

(c) Java Class Definition for CardioWorkout:

public class CardioWorkout extends Workout {
private int averageHeartRate;
private double distance;

public CardioWorkout(String workoutID, int duration, double caloriesBurned, int averageHeartRate, double distance) {
super(workoutID, duration, caloriesBurned);
this.averageHeartRate = averageHeartRate;
this.distance = distance;
}

@Override
public String calculateIntensity() {
if (this.averageHeartRate > 150) {
return "High";
} else if (this.averageHeartRate >= 110) {
return "Medium";
} else {
return "Low";
}
}
}

Marking scheme

Part (a) [3 marks]
- 1 mark: Clear definition of encapsulation (hiding internal state, exposing via public methods).
- 1 mark: Application to Workout (making fields private to prevent external modification).
- 1 mark: Explanation of getter methods acting as controlled access points.

Part (b) [5 marks]
- 1 mark: Correct class declaration and private attributes (workoutID, duration, caloriesBurned) with appropriate types.
- 1 mark: Correct constructor assigning all three parameters using 'this' or different variable names.
- 1 mark: All three correct accessor methods (getWorkoutID, getDuration, getCaloriesBurned) returning correct types.
- 1 mark: Signature and return statement for calculateIntensity() returning "General".
- 1 mark: Syntax accuracy (braces, semicolons, standard Java structure).

Part (c) [7 marks]
- 1 mark: Correct subclass header with 'extends Workout'.
- 1 mark: Subclass private attributes (averageHeartRate as int, distance as double) defined correctly.
- 1 mark: Constructor signature accepting five parameters.
- 1 mark: First statement of constructor is 'super(workoutID, duration, caloriesBurned)'.
- 1 mark: Proper assignment of the subclass fields within the constructor.
- 1 mark: Overriding signature for calculateIntensity() matching the superclass method signature.
- 1 mark: Correct logical conditions using if-else structures to return "High", "Medium", or "Low" according to the specified limits.
Question 2 · inheritance-and-methods
16 marks
A logistics company manages packages using object-oriented programming.

The base class `Delivery` is defined as follows:

```java
public class Delivery {
private String trackingID;
private double weight; // in kg
private String destination;

public Delivery(String trackingID, double weight, String destination) {
this.trackingID = trackingID;
this.weight = weight;
this.destination = destination;
}

public String getTrackingID() { return trackingID; }
public double getWeight() { return weight; }
public String getDestination() { return destination; }

public double calculateCost() {
return 5.00 + (weight * 1.50);
}
}
```

(a) Outline the concept of inheritance and describe how it applies to the relationship between the `Delivery` and `ExpressDelivery` classes. [3]

(b) Write the code for the subclass `ExpressDelivery` which extends `Delivery`.
The subclass should:
- Have an additional private integer attribute `guaranteedHours`.
- Have a constructor that accepts four parameters (`trackingID`, `weight`, `destination`, `guaranteedHours`) and correctly initializes them.
- Override the `calculateCost()` method. The express cost is calculated as the base delivery cost plus an extra fee depending on `guaranteedHours`:
- If `guaranteedHours` is 12, add an extra 20.00 USD.
- If `guaranteedHours` is 24, add an extra 10.00 USD.
- Otherwise, add an extra 5.00 USD. [5]

(c) Explain the difference between method overriding and method overloading, referencing how `calculateCost()` is implemented in this system. [3]

(d) A client class contains an array of `Delivery` objects called `shipments`.
Construct a static method `calculateTotalRevenue(Delivery[] shipments)` that returns the total delivery cost of all shipments in the array as a `double`. Explain how **polymorphism** plays a role during the execution of this method. [5]
Show answer & marking scheme

Worked solution

(a)
Inheritance is an OOP mechanism where a new class (subclass) acquires the properties (attributes) and behaviors (methods) of an existing class (superclass). In this scenario, `ExpressDelivery` is the subclass that inherits from the `Delivery` superclass. It reuses the attributes `trackingID`, `weight`, and `destination`, along with their respective getter methods, and extends the functionality by adding `guaranteedHours` and redefining cost calculations.

(b)
```java
public class ExpressDelivery extends Delivery {
private int guaranteedHours;

public ExpressDelivery(String trackingID, double weight, String destination, int guaranteedHours) {
super(trackingID, weight, destination);
this.guaranteedHours = guaranteedHours;
}

@Override
public double calculateCost() {
double baseCost = super.calculateCost();
if (this.guaranteedHours == 12) {
return baseCost + 20.00;
} else if (this.guaranteedHours == 24) {
return baseCost + 10.00;
} else {
return baseCost + 5.00;
}
}
}
```

(c)
- **Method Overriding** occurs when a subclass provides a specific implementation of a method that is already defined in its parent class, sharing the same signature (name, parameters, and return type). In this scenario, `calculateCost()` in `ExpressDelivery` overrides `calculateCost()` in `Delivery`.
- **Method Overloading** occurs when a class has multiple methods with the same name but different parameter lists (signatures) within the same scope.
- In this scenario, `calculateCost()` is overridden to change behavior based on the object's specific type, rather than overloaded.

(d)
```java
public static double calculateTotalRevenue(Delivery[] shipments) {
double total = 0.0;
for (int i = 0; i < shipments.length; i++) {
if (shipments[i] != null) {
total += shipments[i].calculateCost();
}
}
return total;
}
```
**Polymorphism** allows the array of type `Delivery[]` to contain both `Delivery` and `ExpressDelivery` objects. During execution, when `shipments[i].calculateCost()` is called, **dynamic (late) binding** occurs. The Java Virtual Machine (JVM) dynamically determines the actual subclass type of each object at runtime and executes the correct `calculateCost()` method (either the base class version or the overridden subclass version), ensuring the correct total revenue is calculated automatically without explicit type-casting.

Marking scheme

(a) [3 marks total]
- [1 mark] for defining inheritance (sharing attributes/methods from parent to child class).
- [1 mark] for identifying `Delivery` as the superclass/parent and `ExpressDelivery` as the subclass/child.
- [1 mark] for explaining that `ExpressDelivery` inherits fields (`trackingID`, `weight`, `destination`) and behavior (getters) without redefining them, but extends them with `guaranteedHours`.

(b) [5 marks total]
- [1 mark] for correct class signature: `public class ExpressDelivery extends Delivery`.
- [1 mark] for declaring the private attribute: `private int guaranteedHours;`.
- [1 mark] for correct constructor calling `super(...)` as the first statement.
- [1 mark] for correct method overriding header: `public double calculateCost()`.
- [1 mark] for correct conditional logic using `super.calculateCost()` to compute and return the correct cost based on `guaranteedHours`.

(c) [3 marks total]
- [1 mark] for defining method overriding (same name and parameters in subclass, replacing parent behavior) and referencing `calculateCost()` as overridden.
- [1 mark] for defining method overloading (same name but different parameters within the same class context).
- [1 mark] for clarifying that `calculateCost()` in this implementation is overridden to implement specialized subclass logic, not overloaded.

(d) [5 marks total]
- [1 mark] for correct static method signature and double return type.
- [1 mark] for initializing the accumulator variable to `0.0` and returning it at the end.
- [1 mark] for a valid loop iterating through the `shipments` array.
- [1 mark] for invoking `calculateCost()` on the element and adding it to the accumulator.
- [1 mark] for explaining how polymorphism/dynamic binding executes the correct version of `calculateCost()` at runtime based on the actual object type without explicit casting.
Question 3 · oop-algorithm-sorting
14 marks
A travel agency uses an object-oriented system to manage and display flight information at an airport. The system uses a \`Flight\` class to represent individual flights, and an \`AirportBoard\` class to manage an array of these flights.

The class outlines are defined as follows:

```java
public class Flight {
private String flightNumber;
private String destination;
private int delayMinutes;

public Flight(String flightNumber, String destination, int delayMinutes) {
this.flightNumber = flightNumber;
this.destination = destination;
this.delayMinutes = delayMinutes;
}

public String getFlightNumber() { return flightNumber; }
public String getDestination() { return destination; }
public int getDelayMinutes() { return delayMinutes; }
}
```

```java
public class AirportBoard {
private Flight[] flights; // may contain nulls at the end
private int count; // actual number of Flight objects currently in the array

public AirportBoard(int capacity) {
flights = new Flight[capacity];
count = 0;
}

// Assume accessors, mutators, and other methods are implemented
}
```

(a) Explain why a standard bubble sort algorithm designed for primitive integers cannot be directly applied to the \`flights\` array. [2 marks]

(b) Construct the Java code for the method \`sortByDelayDescending()\` within the \`AirportBoard\` class. This method must sort the active flights in-place in *descending* order of their \`delayMinutes\` using a selection sort algorithm. You must ensure you only sort up to \`count\` elements to avoid \`NullPointerException\`s. [6 marks]

(c) The airport wishes to enhance the sorting criteria: if two flights have the same delay, they should be sorted alphabetically (A to Z) by their \`destination\`. Construct the updated conditional comparison statement(s) that would replace the single delay comparison in your sorting algorithm. [4 marks]

(d) State the complexity of the selection sort in the worst-case scenario using Big-O notation, and justify your answer by referring to the comparisons made by the algorithm. [2 marks]
Show answer & marking scheme

Worked solution

### Part (a) Solution
In Java, primitive sorting algorithms compare numbers directly using relational operators (e.g., \`>\`, \`<\`).
1. Objects cannot be compared directly using these relational operators because the operators evaluate object reference memory addresses rather than internal object values.
2. To sort objects, the program must explicitly target and compare specific attributes of the object (such as \`delayMinutes\`) by invoking its accessor methods (like \`getDelayMinutes()\`).

### Part (b) Solution
```java
public void sortByDelayDescending() {
for (int i = 0; i < count - 1; i++) {
int maxIdx = i;
for (int j = i + 1; j < count; j++) {
// Compare the delayMinutes of elements at index j and maxIdx
if (flights[j].getDelayMinutes() > flights[maxIdx].getDelayMinutes()) {
maxIdx = j;
}
}
// Swap flights[i] and flights[maxIdx]
Flight temp = flights[i];
flights[i] = flights[maxIdx];
flights[maxIdx] = temp;
}
}
```

### Part (c) Solution
To handle the secondary sort alphabetically (A-Z) on destination when delays are identical:
```java
if (flights[j].getDelayMinutes() > flights[maxIdx].getDelayMinutes()) {
maxIdx = j;
} else if (flights[j].getDelayMinutes() == flights[maxIdx].getDelayMinutes()) {
// If delays are equal, sort alphabetically (A comes before B, so compareTo returns negative value)
if (flights[j].getDestination().compareTo(flights[maxIdx].getDestination()) < 0) {
maxIdx = j;
}
}
```

### Part (d) Solution
- **Big-O Complexity:** \(O(N^2)\) (or \(O(\text{count}^2)\))
- **Justification:** Selection sort uses nested loops. The outer loop runs \(N-1\) times, and the inner loop performs comparisons that decrease in count with each step: \((N-1) + (N-2) + \dots + 1\). This results in a total of \(\frac{N(N-1)}{2}\) comparisons. Since this number is proportional to \(N^2\), the time complexity is quadratic in all cases, including the worst case.

Marking scheme

### Part (a) [2 marks]
- **1 mark** for stating that relational operators (\`>\`, \`<\`) cannot be applied directly to object references.
- **1 mark** for stating that comparisons must extract and compare the inner fields of the object using accessor/getter methods (e.g., \`getDelayMinutes()\`).

### Part (b) [6 marks]
- **1 mark** for correct outer loop boundaries (from \`0\` up to \`count - 1\` or equivalent).
- **1 mark** for correct initialization of tracking variable (e.g., \`int maxIdx = i\`).
- **1 mark** for correct inner loop starting from \`i + 1\` and terminating at \`count\` (to avoid null references).
- **1 mark** for calling \`getDelayMinutes()\` on array elements during comparison.
- **1 mark** for evaluating the condition in descending order (checking if \`j\`'s delay is larger than current max index's delay).
- **1 mark** for a correct swap algorithm using a temporary variable of type \`Flight\`.

### Part (c) [4 marks]
- **1 mark** for checking if the delay times are equal (detecting a tie-breaker situation).
- **1 mark** for calling \`getDestination()\` on both \`Flight\` objects.
- **1 mark** for correctly using the \`.compareTo()\` method (or equivalent string comparison mechanism) on the destinations.
- **1 mark** for checking for a negative result (\`< 0\`) from \`compareTo()\` to prioritize alphabetical order, and correctly updating the index tracker (\`maxIdx\`).

### Part (d) [2 marks]
- **1 mark** for identifying the complexity as \(O(N^2)\) or \(O(\text{count}^2)\).
- **1 mark** for justifying that selection sort uses nested loops, yielding a number of comparisons proportional to \(N^2\) (or mathematically representing \(\frac{N(N-1)}{2}\) operations).

Wondering how well you actually know this?

Thinka is an AI practice app for DSE students — unlimited questions, instant auto-marking, and detailed step-by-step solutions. 100,000+ students use it to confirm they actually know it, not just think they do.

Want more questions like this? Practice unlimited on Thinka — instant answers included.

Start Practising Free