Cambridge IAS-Level · Thinka 原創模擬試題

2023 Cambridge IAS-Level Computer Science (9618) 模擬試題連答案詳解

Thinka Jun 2023 (V2) Cambridge International A Level-Style Mock — Computer Science (9618)

150 210 分鐘2023
An original Thinka practice paper modelled on the structure and difficulty of the Jun 2023 (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.
9 題目 · 90
題目 1 · structured
11
An office layout requires a Local Area Network (LAN) to connect several devices.

(a) Describe the structure of a star topology LAN by explaining how four workstation computers, a shared file server, and a network printer would be connected to a central switch. [4 marks]

(b) Explain how the central switch directs data packages to specific workstations, and how this process differs from using a hub. [4 marks]

(c) Identify two advantages and one disadvantage of using a star topology instead of a bus topology. [3 marks]
查看答案詳解

解題

Part (a): In a star topology, all devices are connected directly to a central node (the switch) via individual, dedicated point-to-point cables. Specifically, the four workstation computers, the shared file server, and the network printer will each have their own independent cable run connecting them directly to separate ports on the central switch. There are no direct physical connections between the workstations themselves.

Part (b): A switch functions at the Data Link layer of the OSI model. When it receives a data packet, it reads the destination MAC address from the packet header. It looks up this address in its MAC address table (or routing table) to find the specific port associated with that MAC address and forwards the packet only to that port. In contrast, a hub is a non-intelligent device that does not read MAC addresses; when it receives data on one port, it broadcasts (copies) that data to all other ports, forcing all connected devices to receive and discard the packet if it is not addressed to them.

Part (c):
Advantages of a star topology compared to a bus topology:
1. High fault tolerance: If a single cable connecting a workstation to the switch fails, only that workstation is disconnected, while the rest of the network continues to function normally (on a bus network, a cable break can bring down the entire network segment).
2. Security and performance: Data is sent directly to the destination device rather than being broadcast across a shared medium, which prevents unauthorized packet sniffing and reduces data collisions.
Disadvantage:
1. Single point of failure: If the central switch fails, the entire network becomes completely inoperable.

評分準則

Part (a) [Max 4 marks]:
- 1 mark: Identifying the switch as the central node in the star topology.
- 1 mark: Stating that each workstation (4 in total) has a dedicated/point-to-point connection to the switch.
- 1 mark: Stating that both the file server and the printer are also connected directly to the central switch.
- 1 mark: Mentioning that there are no direct connections between the individual peripheral devices / communication must pass through the central switch.

Part (b) [Max 4 marks]:
- 1 mark: Switch reads the destination MAC address from the incoming data packet.
- 1 mark: Switch sends the packet only to the specific port/device corresponding to that destination MAC address.
- 1 mark: Hub does not read MAC addresses/destinations (operates at physical layer).
- 1 mark: Hub broadcasts/transmits incoming data to all connected devices/ports.

Part (c) [Max 3 marks]:
- 1 mark: For each of two valid advantages (e.g., failure of one cable/device does not affect other devices, easier to add/remove devices without disruption, lower rates of data collision, better security as data is not broadcast to all).
- 1 mark: For one valid disadvantage (e.g., central switch represents a single point of failure, higher installation cost due to more physical cabling compared to a bus topology).
題目 2 · structured
11
An office layout requires a Local Area Network (LAN) to connect several devices.

(a) Describe how four workstation computers, a shared file server, and a network printer would be connected to a central switch in a star topology. [4 marks]

(b) Explain how the central switch directs data packages to specific workstations, and how this process differs from using a hub. [4 marks]

(c) Identify two advantages and one disadvantage of using a star topology instead of a bus topology. [3 marks]
查看答案詳解

解題

Part (a): In a star topology, all devices are connected directly to a central node (the switch) via individual, dedicated point-to-point cables. Specifically, the four workstation computers, the shared file server, and the network printer will each have their own independent cable run connecting them directly to separate ports on the central switch. There are no direct physical connections between the workstations themselves.

Part (b): A switch functions at the Data Link layer of the OSI model. When it receives a data packet, it reads the destination MAC address from the packet header. It looks up this address in its MAC address table to find the specific port associated with that MAC address and forwards the packet only to that port. In contrast, a hub is a non-intelligent device that does not read MAC addresses; when it receives data on one port, it broadcasts (copies) that data to all other ports, forcing all connected devices to receive and check the packet.

Part (c):
Advantages of a star topology compared to a bus topology:
1. High fault tolerance: If a single cable connecting a workstation to the switch fails, only that workstation is disconnected, while the rest of the network continues to function normally.
2. Security and performance: Data is sent directly to the destination device rather than being broadcast across a shared medium, reducing data collisions.
Disadvantage:
1. Single point of failure: If the central switch fails, the entire network becomes completely inoperable.

評分準則

Part (a) [Max 4 marks]:
- 1 mark: Identifying the switch as the central node.
- 1 mark: Stating that each workstation has a dedicated/point-to-point connection to the switch.
- 1 mark: Stating that both the file server and the printer are also connected directly to the central switch.
- 1 mark: Mentioning that there are no direct connections between the individual peripheral devices.

Part (b) [Max 4 marks]:
- 1 mark: Switch reads the destination MAC address from the incoming data packet.
- 1 mark: Switch sends the packet only to the specific port/device corresponding to that destination MAC address.
- 1 mark: Hub does not read MAC addresses/destinations.
- 1 mark: Hub broadcasts/transmits incoming data to all connected devices/ports.

Part (c) [Max 3 marks]:
- 1 mark: For each of two valid advantages (e.g., failure of one cable/device does not affect other devices, easier to add/remove devices without disruption, lower rates of data collision, better security as data is not broadcast to all).
- 1 mark: For one valid disadvantage (e.g., central switch represents a single point of failure, higher installation cost due to more physical cabling compared to a bus topology).
題目 3 · structured
17
A veterinary clinic uses a relational database to store data about owners, pets, and appointments.

The database design includes three tables:
- `OWNER(OwnerID, FirstName, LastName, PhoneNumber, EmailAddress)`
- `PET(PetID, PetName, Species, DateOfBirth, OwnerID)`
- `APPOINTMENT(AppointmentID, ApptDate, ApptTime, PetID, TreatmentFee)`

(a) (i) Identify the relationship between the `OWNER` table and the `PET` table. [1]
(ii) Identify the relationship between the `PET` table and the `APPOINTMENT` table. [1]
(iii) Explain why a direct relationship link is not required between the `OWNER` and `APPOINTMENT` tables. [1]

(b) (i) Identify the primary key and the foreign key for the `PET` table. [2]
(ii) Explain the term *referential integrity* and describe how it applies to the `OWNER` and `PET` tables when a new pet record is added. [3]

(c) State one suitable validation check that could be performed on each of the following fields in the database. Describe how the validation check would prevent invalid data from being entered.
(i) `TreatmentFee` [1]
(ii) `DateOfBirth` [1]
(iii) `OwnerID` [1]

(d) (i) Write an SQL script to create the `PET` table.
- `PetID` and `OwnerID` are text fields of fixed length 6.
- `PetName` and `Species` are text fields of variable length up to 30 characters.
- `DateOfBirth` is a date field.
- Define primary and foreign key constraints. [3]
(ii) Write an SQL query to retrieve the `PetName` and the total sum of all their `TreatmentFee`s (aliased as 'TotalSpent') for pets whose species is 'Cat'. The results must be grouped by `PetName`. [3]
查看答案詳解

解題

(a) (i) One-to-many relationship (1:M) from OWNER to PET. (1 owner can have 0, 1, or many pets, but each pet belongs to exactly 1 owner).
(ii) One-to-many relationship (1:M) from PET to APPOINTMENT. (1 pet can have many appointments, but each appointment is for exactly 1 pet).
(iii) The relationship is indirect and resolved through the PET table. Because PET contains OwnerID and APPOINTMENT contains PetID, the owner of any appointment can be determined by tracing the foreign keys without requiring a direct link.

(b) (i) Primary key: PetID. Foreign key: OwnerID.
(ii) Referential integrity is a measure of the consistency and accuracy of data in a relational database, ensuring that a foreign key value always points to an existing primary key value in the referenced table (or is null). When a new pet record is added, the system checks that the OwnerID entered exists in the OWNER table; if it does not exist, the record insertion is rejected to prevent 'orphan' records.

(c) (i) TreatmentFee: Range check (e.g., must be >= 0.00) to ensure negative fees are not entered.
(ii) DateOfBirth: Range check / Limit check (e.g., must be in the past / <= current date) to prevent future dates from being entered.
(iii) OwnerID: Presence check (cannot be left blank) to ensure every pet is linked to an owner, OR Length/Format check (must be exactly 6 characters) to match the ID structure.

(d) (i)
CREATE TABLE PET (
PetID CHAR(6) NOT NULL,
PetName VARCHAR(30),
Species VARCHAR(30),
DateOfBirth DATE,
OwnerID CHAR(6) NOT NULL,
PRIMARY KEY (PetID),
FOREIGN KEY (OwnerID) REFERENCES OWNER(OwnerID)
);

(ii)
SELECT PET.PetName, SUM(APPOINTMENT.TreatmentFee) AS TotalSpent
FROM PET
INNER JOIN APPOINTMENT ON PET.PetID = APPOINTMENT.PetID
WHERE PET.Species = 'Cat'
GROUP BY PET.PetName;

評分準則

(a)
(i) 1 mark for identifying One-to-many (1:M) from OWNER to PET.
(ii) 1 mark for identifying One-to-many (1:M) from PET to APPOINTMENT.
(iii) 1 mark for explaining that the relationship is indirect / resolved through the PET table (since PET contains OwnerID and APPOINTMENT contains PetID).

(b)
(i) 1 mark for Primary key: PetID. 1 mark for Foreign key: OwnerID.
(ii) 1 mark for explaining that referential integrity ensures a foreign key value must match an existing primary key value. 1 mark for explaining the check on OwnerID when a new pet is added. 1 mark for explaining that the insertion is blocked/rejected if the OwnerID does not exist.

(c)
(i) 1 mark for Range check (>= 0) or Type check (Real/Currency).
(ii) 1 mark for Range/Limit check (must be in the past / <= current date).
(iii) 1 mark for Presence check (cannot be null) or Length/Format check (6 characters).

(d)
(i) 3 marks total:
- 1 mark for correct CREATE TABLE PET with field names and data types (CHAR(6), VARCHAR(30), DATE).
- 1 mark for PRIMARY KEY (PetID).
- 1 mark for FOREIGN KEY (OwnerID) REFERENCES OWNER(OwnerID).
(ii) 3 marks total:
- 1 mark for SELECT PetName, SUM(TreatmentFee) AS TotalSpent.
- 1 mark for joining tables correctly using INNER JOIN ON or WHERE clause equivalence.
- 1 mark for WHERE Species = 'Cat' AND GROUP BY PetName.
題目 4 · written
6
An assembler is a piece of utility software used to translate assembly language into machine code. Most assemblers perform this process in two passes. (a) Describe the main activities performed by an assembler during: (i) the first pass [2] (ii) the second pass [2] (b) Assembly language instructions use different addressing modes to reference memory locations. Describe the difference between direct addressing and indexed addressing. [2]
查看答案詳解

解題

Part (a)(i): In Pass 1, the assembler scans the source code sequentially. Its primary task is to construct the symbol table. It looks for labels (identifiers), determines their memory addresses using a location counter, and saves these pairs in the symbol table. It also strips out comments, expands macro definitions, and performs basic syntax checking.

Part (a)(ii): In Pass 2, the assembler scans the code again. It converts symbolic operation codes (like ADD, LDX) into their binary representation. It uses the symbol table constructed during Pass 1 to replace any symbolic labels/operands with their calculated numeric addresses. Finally, it outputs the object code (executable file) and any assembly errors that could not be resolved.

Part (b): Direct addressing refers to a memory access method where the address field of the instruction contains the target memory address directly (e.g., LDD 200 loads contents of memory address 200). Indexed addressing calculates the target memory address dynamically by adding the base address specified in the instruction to the current value stored in the Index Register (IX) (e.g., LDX 200 with IX = 5 accesses memory address 205).

評分準則

Part (a)(i): Max 2 marks:
- Reads the source code line by line / scans the program [1]
- Builds a symbol table to store identifiers/labels and their addresses [1]
- Allocates memory addresses / increments the location counter [1]
- Detects syntax errors [1]

Part (a)(ii): Max 2 marks:
- Translates symbolic opcodes / mnemonics into binary machine code [1]
- Resolves symbolic references / replaces labels with addresses from the symbol table [1]
- Generates the final object code / executable file [1]

Part (b): Max 2 marks:
- Direct addressing: the instruction contains the actual/absolute memory address of the operand [1]
- Indexed addressing: the instruction specifies a base address which is added to the contents of the Index Register (IX) to determine the effective address [1]
題目 5 · written
6
Part (a) Convert the denary value -43 into an 8-bit two's complement binary integer. Show your working. Part (b) Perform an arithmetic right shift by 2 places on your 8-bit binary representation from Part (a). Show your working. Part (c) Convert the resulting binary pattern from Part (b) back into denary, and explain how the mathematical result of this shift relates to the original value of -43.
查看答案詳解

解題

Part (a): Start with the positive denary value 43. In 8-bit unsigned binary, 43 is 00101011 (since 32 + 8 + 2 + 1 = 43). To convert this to two's complement, invert all the bits to get 11010100. Then, add 1 to the least significant bit, which results in 11010101. Part (b): To perform an arithmetic right shift by 2 places on 11010101, move all bits two positions to the right. Because it is an arithmetic shift, the vacated bit positions on the left must be filled with copies of the original sign bit, which is 1. Shifting right once gives 11101010. Shifting right a second time gives 11110101. Part (c): Convert 11110101 back to denary. Since the sign bit (most significant bit) is 1, it is a negative number. Invert the bits to get 00001010, then add 1 to get 00001011, which represents the magnitude 11. Therefore, the value is -11. Mathematically, an arithmetic right shift by n places is equivalent to division by 2^n with the result rounded down to the next lowest integer (floor division). For n = 2, this is division by 4. -43 / 4 = -10.75, which rounds down to -11.

評分準則

Part (a): 1 mark for showing a valid method (e.g., finding +43 in binary and inverting bits). 1 mark for the correct final binary representation: 11010101. Part (b): 1 mark for performing a right shift where the vacated sign bits are filled with 1s (maintaining sign). 1 mark for the correct shifted pattern: 11110101. Part (c): 1 mark for the correct denary value of -11. 1 mark for explaining that arithmetic right shift by 2 is equivalent to division by 4 with the result rounded down to the next integer.
題目 6 · structured
15
A small architectural design company uses workstations that run a multitasking operating system. The workstations are currently running slowly when complex 3D rendering tasks are performed. The company is considering hardware upgrades and wants to understand how the system software manages resources.

(a) The workstations use processors based on the Von Neumann architecture.
During the fetch-execute cycle, registers are used to manage instruction execution.
Identify two registers used during the fetch stage and describe their roles. [4]

(b) The company is considering two upgrade options:
- Option 1: Increase the capacity of the Random Access Memory (RAM).
- Option 2: Replace the processor with one that has a higher clock speed.
Explain how each of these options could improve the workstation's performance. [4]

(c) The operating system uses process management to handle multiple active programs.
(i) Identify and describe the three main process states in a multitasking operating system. [3]
(ii) State the name of the data structure used by the operating system to keep track of all the information needed to manage each process. [1]

(d) Describe the role of interrupts in process management when a running process requests a slow input/output (I/O) operation, such as saving a large design file to secondary storage. [3]
查看答案詳解

解題

Part (a)
Any two registers from:
1. Program Counter (PC): Stores the address of the next instruction to be fetched from memory.
2. Memory Address Register (MAR): Holds the memory address of the instruction currently being fetched, or data currently being read from/written to memory.
3. Memory Data Register (MDR): Holds the data or instruction that has just been fetched from memory, or is waiting to be written to memory.
4. Current Instruction Register (CIR): Holds the instruction that has been fetched from memory and is currently being decoded.

Part (b)
- Option 1 (RAM upgrade): Increasing RAM capacity allows more of the rendering assets and instructions to be kept in fast main memory. This significantly reduces the need to use slow virtual memory on secondary storage, avoiding disk thrashing and page faults.
- Option 2 (Clock speed upgrade): Replacing the processor with one of higher clock speed increases the number of clock cycles per second. This allows the CPU to perform more FDE cycles per second, accelerating the computation of CPU-intensive tasks such as 3D rendering calculations.

Part (c)
- (i) Process States:
- Running: The process is currently executing instructions on the CPU.
- Ready: The process is loaded in memory and waiting to be allocated CPU time by the scheduler.
- Blocked (or Waiting): The process is suspended and cannot proceed because it is waiting for an external event (such as an I/O operation or user input).
- (ii) Data Structure:
- Process Control Block (PCB) (or Process Table).

Part (d)
- When a running process makes an I/O request, it triggers a software interrupt (or system call).
- The operating system interrupts the CPU, saves the current context of the process, and moves its state from Running to Blocked so it does not waste valuable CPU cycles.
- The operating system's scheduler allocates the CPU to another process from the Ready queue (context switch).
- Once the slow I/O operation completes, a hardware interrupt is sent to the CPU, prompting the operating system to transition the blocked process back to the Ready state, allowing it to compete for CPU time again.

評分準則

Part (a) [4 Marks]
- 1 mark for identifying a valid register (max 2)
- 1 mark for its correct role during the fetch stage (max 2)
Acceptable Registers: PC, MAR, MDR, CIR.
Reject: Accumulator (ACC) or Index Register (IX) as they are not primarily involved in the fetch stage.

Part (b) [4 Marks]
- RAM Upgrade: 1 mark for mentioning more data/programs stored in main memory simultaneously; 1 mark for mentioning reduced reliance on virtual memory / less disk thrashing.
- Clock Speed: 1 mark for explaining that it increases the number of clock pulses/cycles per second; 1 mark for explaining that more instructions are executed per second / speeds up computation of 3D rendering.

Part (c) [4 Marks]
- (i) States: 1 mark for each correct state with its explanation (max 3):
- Running: currently executing instructions on CPU.
- Ready: waiting in queue for CPU allocation.
- Blocked: waiting for I/O / event to complete.
- (ii) Data Structure: 1 mark for Process Control Block (PCB) or Process Table.

Part (d) [3 Marks]
- 1 mark: Running process issues a system call / interrupt for I/O.
- 1 mark: Operating system moves the process from Running to Blocked state and schedules another process (context switch).
- 1 mark: Once I/O completes, an interrupt is sent, and the OS moves the process back to the Ready state.
題目 7 · table-completion
4
A logic circuit has three inputs, \(A\), \(B\), and \(C\). The logic expression for the output \(X\) is:

\(X = (A \text{ AND } \text{NOT } B) \text{ NOR } (B \text{ XOR } C)\)

Complete the truth table for this logic expression.

| A | B | C | Working space 1
(\(A \text{ AND } \text{NOT } B\)) | Working space 2
(\(B \text{ XOR } C\)) | Output \(X\) |
|---|---|---|---|---|---|
| 0 | 0 | 0 | | | |
| 0 | 0 | 1 | | | |
| 0 | 1 | 0 | | | |
| 0 | 1 | 1 | | | |
| 1 | 0 | 0 | | | |
| 1 | 0 | 1 | | | |
| 1 | 1 | 0 | | | |
| 1 | 1 | 1 | | | |
查看答案詳解

解題

To complete the truth table, we evaluate the logic expression step-by-step for each of the 8 rows:

1. **Evaluate Working space 1: \(P = A \text{ AND } \text{NOT } B\)**
- This output is 1 only when \(A = 1\) and \(B = 0\).
- This occurs in rows 5 and 6 (inputs 1,0,0 and 1,0,1). For all other rows, the output is 0.
- Column values: `0, 0, 0, 0, 1, 1, 0, 0`

2. **Evaluate Working space 2: \(Q = B \text{ XOR } C\)**
- This output is 1 when \(B\) and \(C\) have different logic states.
- This occurs in row 2 (0,0,1), row 3 (0,1,0), row 6 (1,0,1), and row 7 (1,1,0).
- Column values: `0, 1, 1, 0, 0, 1, 1, 0`

3. **Evaluate Output \(X = P \text{ NOR } Q\)**
- The NOR gate outputs 1 only when both intermediate values \(P\) and \(Q\) are 0.
- Row 1 (0,0,0): \(0 \text{ NOR } 0 = 1\)
- Row 2 (0,0,1): \(0 \text{ NOR } 1 = 0\)
- Row 3 (0,1,0): \(0 \text{ NOR } 1 = 0\)
- Row 4 (0,1,1): \(0 \text{ NOR } 0 = 1\)
- Row 5 (1,0,0): \(1 \text{ NOR } 0 = 0\)
- Row 6 (1,0,1): \(1 \text{ NOR } 1 = 0\)
- Row 7 (1,1,0): \(0 \text{ NOR } 1 = 0\)
- Row 8 (1,1,1): \(0 \text{ NOR } 0 = 1\)
- Column values: `1, 0, 0, 1, 0, 0, 0, 1`

評分準則

- 1 mark for correct column for 'Working space 1' (0, 0, 0, 0, 1, 1, 0, 0).
- 1 mark for correct column for 'Working space 2' (0, 1, 1, 0, 0, 1, 1, 0).
- 2 marks for correct 'Output X' column (1, 0, 0, 1, 0, 0, 0, 1).
- (Award 1 mark if there are 1 or 2 errors in Output X column, or if Output X is correctly derived from incorrect working columns).
題目 8 · table-completion
4
A logic circuit has three inputs, \(A\), \(B\), and \(C\). The logic expression for the output \(X\) is:

\(X = (A \text{ AND } \text{NOT } B) \text{ NOR } (B \text{ XOR } C)\)

Complete the truth table for this logic expression.

| A | B | C | Working space 1
(\(A \text{ AND } \text{NOT } B\)) | Working space 2
(\(B \text{ XOR } C\)) | Output \(X\) |
|---|---|---|---|---|---|
| 0 | 0 | 0 | | | |
| 0 | 0 | 1 | | | |
| 0 | 1 | 0 | | | |
| 0 | 1 | 1 | | | |
| 1 | 0 | 0 | | | |
| 1 | 0 | 1 | | | |
| 1 | 1 | 0 | | | |
| 1 | 1 | 1 | | | |
查看答案詳解

解題

To complete the truth table, we evaluate the logic expression step-by-step for each of the 8 rows:

1. **Evaluate Working space 1: \(P = A \text{ AND } \text{NOT } B\)**
- This output is 1 only when \(A = 1\) and \(B = 0\).
- This occurs in rows 5 and 6 (inputs 1,0,0 and 1,0,1). For all other rows, the output is 0.
- Column values: `0, 0, 0, 0, 1, 1, 0, 0`

2. **Evaluate Working space 2: \(Q = B \text{ XOR } C\)**
- This output is 1 when \(B\) and \(C\) have different logic states.
- This occurs in row 2 (0,0,1), row 3 (0,1,0), row 6 (1,0,1), and row 7 (1,1,0).
- Column values: `0, 1, 1, 0, 0, 1, 1, 0`

3. **Evaluate Output \(X = P \text{ NOR } Q\)**
- The NOR gate outputs 1 only when both intermediate values \(P\) and \(Q\) are 0.
- Row 1 (0,0,0): \(0 \text{ NOR } 0 = 1\)
- Row 2 (0,0,1): \(0 \text{ NOR } 1 = 0\)
- Row 3 (0,1,0): \(0 \text{ NOR } 1 = 0\)
- Row 4 (0,1,1): \(0 \text{ NOR } 0 = 1\)
- Row 5 (1,0,0): \(1 \text{ NOR } 0 = 0\)
- Row 6 (1,0,1): \(1 \text{ NOR } 1 = 0\)
- Row 7 (1,1,0): \(0 \text{ NOR } 1 = 0\)
- Row 8 (1,1,1): \(0 \text{ NOR } 0 = 1\)
- Column values: `1, 0, 0, 1, 0, 0, 0, 1`

評分準則

- 1 mark for correct column for 'Working space 1' (0, 0, 0, 0, 1, 1, 0, 0).
- 1 mark for correct column for 'Working space 2' (0, 1, 1, 0, 0, 1, 1, 0).
- 2 marks for correct 'Output X' column (1, 0, 0, 1, 0, 0, 0, 1).
- (Award 1 mark if there are 1 or 2 errors in Output X column, or if Output X is correctly derived from incorrect working columns).
題目 9 · structured
16
An independent software developer is creating a simulation application using a high-level programming language. (a) State two differences between a compiler and an interpreter. [4] (b) The developer decides to use pre-compiled library files. (i) Describe two benefits of using library files. [4] (ii) Explain the roles of a linker and a loader in relation to these library files. [4] (c) The developer uses an Integrated Development Environment (IDE) to write and test the code. Identify two features of an IDE that can assist the developer in identifying and correcting errors in their source code, and explain how each feature helps. [4]
查看答案詳解

解題

Part (a): - A compiler translates the entire source code into machine code (object code) in one single operation, whereas an interpreter translates and executes the source code line-by-line. - A compiler produces an independent executable file (the source code is no longer needed to run the program), whereas an interpreter does not produce an executable file and requires both the source code and the interpreter to run the program. - A compiler produces an error report only after scanning the entire code, whereas an interpreter halts execution immediately when the first error is encountered. Part (b)(i): - Saves development time: The code is already written, tested, and debugged, allowing the developer to focus on other parts of the system. - Reliability and optimization: Library routines are typically written by experts and have been extensively tested and optimized for performance. - Reusability: The same library files can be linked and reused across multiple distinct projects. Part (b)(ii): - Linker: Combines the compiled object code of the main program with the pre-compiled library files into a single executable file. It resolves any external references to library subroutines. - Loader: Copies the compiled executable file from secondary storage (e.g., hard drive) into primary memory (RAM) so that it is ready for the CPU to execute. It also handles memory address relocation where necessary. Part (c): - Feature 1: Breakpoints / Single-stepping. Explanation: Allows the programmer to pause program execution at a specific line of code and step through it line-by-line to monitor the execution flow and isolate where logical errors occur. - Feature 2: Watch Window / Variable Watch. Explanation: Displays the values of selected variables in real-time as the program executes, helping the developer verify that data is being processed correctly and identify where incorrect values originate. - Feature 3: Dynamic Syntax Checking / Real-time Error Underlining. Explanation: Highlights syntax errors immediately as the programmer types, allowing them to correct mistakes before attempting to compile or run the program.

評分準則

Part (a): Award up to 4 marks. 1 mark per distinct, valid comparison (max 2 comparisons). Must compare both compiler and interpreter for each mark. Part (b)(i): Award up to 4 marks. 1 mark for identifying a benefit, 1 mark for describing/expanding it (Max 2 benefits). Part (b)(ii): Award up to 4 marks. Max 2 marks for the role of the linker (combining object code and library code, resolving external references, producing an executable file). Max 2 marks for the role of the loader (loading executable from secondary storage to RAM, adjusting physical memory addresses). Part (c): Award up to 4 marks. 1 mark for identifying an appropriate IDE feature, 1 mark for explaining how it helps locate/correct errors (Max 2 features). Acceptable features: Breakpoints, Single-stepping, Watch window/Variable tracker, Dynamic syntax checking/Auto-compile error highlighting, Call stack. Reject general features like 'Text editor' or 'Auto-complete' unless specifically explained in the context of error correction/prevention.

Paper 22: Problem-Solving and Programming Skills

Answer all questions. Refer to the insert for pseudocode functions.
8 題目 · 75
題目 1 · structured
10
The following pseudocode procedure calculates the rental cost of a bicycle, applying a weekend surcharge and a discount for club members. However, the code is poorly written and lacks readability features.

PROCEDURE Calc(d, w, m)
DECLARE x : REAL
x <- d * 15.50
IF w = TRUE THEN
x <- x + 5.00
ENDIF
IF m = TRUE THEN
x <- x * 0.90
ENDIF
OUTPUT x
ENDPROCEDURE

(a) Identify three distinct features of the given pseudocode that reduce its readability. [3]

(b) (i) Identify two numerical literal values in the pseudocode that should be declared as constants. Describe the purpose of each. [2]
(ii) Write the pseudocode declarations to define these two constants. [2]

(c) Rewrite the pseudocode procedure to improve its readability. Your solution must:
- Use meaningful identifiers for the procedure name, parameters, and variables.
- Incorporate the constants defined in part (b).
- Use correct indentation and formatting. [3]
查看答案詳解

解題

Part (a):
The code suffers from poor styling. The variables 'd', 'w', 'm', and 'x' give no context to their purpose. There is no indentation inside the conditional blocks, making it hard to follow the logic flow. Lastly, hardcoded numerical literals like 15.50, 5.00, and 0.90 make the code difficult to maintain.

Part (b):
(i) 15.50 is the daily rate; 5.00 is the weekend surcharge; 0.90 is the membership discount rate.
(ii) In Cambridge pseudocode, constants are declared using the CONSTANT keyword:
CONSTANT DAILY_RATE = 15.50
CONSTANT WEEKEND_SURCHARGE = 5.00

Part (c):
We rewrite the procedure by declaration of constants, using sensible variable names like 'RentalDays', 'IsWeekend', 'IsMember', and 'TotalCost', and indenting code blocks inside the procedure and the IF statements appropriately.

評分準則

Part (a) [Max 3 marks]:
- Meaningless/non-descriptive variable or procedure names.
- Lack of indentation (within IF blocks or the PROCEDURE).
- Use of hardcoded literal numbers / "magic numbers" (e.g., 15.50, 5.00).
- Absence of explanatory comments / blank lines to separate logic.

Part (b)(i) [2 marks]:
- 1 mark for each identified literal value with its correct description (Max 2).
- 15.50: Standard daily rental rate.
- 5.00: Weekend surcharge fee.
- 0.90: Member discount multiplier.

Part (b)(ii) [2 marks]:
- 1 mark for each correct CONSTANT declaration matching CAIE pseudocode standards (e.g., CONSTANT = ).

Part (c) [3 marks]:
- 1 mark: Correct constant usage in the logic instead of hardcoded numbers.
- 1 mark: Appropriate parameters and variable names with clear readability and proper indentation throughout.
- 1 mark: Correct program logic preserved (correct multiplication, addition, and final output).
題目 2 · written-essay
9
A software system for an office maintenance department tracks service schedules. The system has access to a global 1-dimensional array, `WeekdayNames`, which is initialized as follows:

* `WeekdayNames : ARRAY[1:7] OF STRING`
* Populated with: `["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]` (where index 1 represents Sunday, index 2 represents Monday, etc.)

The following built-in date-processing functions are available in the programming language library:

| Function | Description |
| :--- | :--- |
| `ADDDAYS(DateVal : DATE, Days : INTEGER) RETURNS DATE` | Adds an integer number of days to a given date and returns the new date. |
| `DAYOFWEEK(DateVal : DATE) RETURNS INTEGER` | Returns an integer representing the day of the week for `DateVal` (1 = Sunday, 2 = Monday, ..., 7 = Saturday). |
| `GETDATESTRING(DateVal : DATE) RETURNS STRING` | Converts a date object to a string format of `"DD/MM/YYYY"`. |

Write pseudocode for a function `GetNextWorkingService` that takes two parameters: `LastService` (of type `DATE`) and `DaysToAdd` (of type `INTEGER`).

The function must:
1. Calculate the tentative next service date by adding `DaysToAdd` to `LastService`.
2. Ensure that services are only scheduled on weekdays (Monday to Friday). If the tentative date falls on a weekend (Saturday or Sunday), it must be rolled forward to the next Monday (i.e., if Saturday, add 2 days; if Sunday, add 1 day).
3. Use the `WeekdayNames` array and the date-processing functions to construct and return a string representing the final working service date in the format: `"WeekdayName, DD/MM/YYYY"` (for example: `"Monday, 23/10/2023"`).

Ensure that all variables are declared and appropriate pseudocode standards are followed.
查看答案詳解

解題

An exemplar pseudocode solution is shown below:

```pseudocode
FUNCTION GetNextWorkingService(LastService : DATE, DaysToAdd : INTEGER) RETURNS STRING
DECLARE TargetDate : DATE
DECLARE DayNum : INTEGER

// 1. Calculate the tentative date
TargetDate <- ADDDAYS(LastService, DaysToAdd)
DayNum <- DAYOFWEEK(TargetDate)

// 2. Adjust if the day falls on a weekend
IF DayNum = 7 THEN // Saturday
TargetDate <- ADDDAYS(TargetDate, 2)
ELSE
IF DayNum = 1 THEN // Sunday
TargetDate <- ADDDAYS(TargetDate, 1)
ENDIF
ENDIF

// 3. Re-evaluate weekday index for the adjusted date
DayNum <- DAYOFWEEK(TargetDate)

// 4. Construct and return the final string
RETURN WeekdayNames[DayNum] & ", " & GETDATESTRING(TargetDate)
ENDFUNCTION
```

評分準則

Award up to 9 marks for the following points:

* **1 Mark**: Correct `FUNCTION` header declaring both parameters with their correct types (`DATE`, `INTEGER`) and a `RETURNS STRING` clause.
* **1 Mark**: Correct local variable declarations (`DECLARE TargetDate : DATE` and `DECLARE DayNum : INTEGER`).
* **1 Mark**: Correct use of the `ADDDAYS` library function to compute the initial tentative `TargetDate`.
* **1 Mark**: Correct call to `DAYOFWEEK(TargetDate)` to find the day of the week.
* **1 Mark**: Correct condition/logic to check for Saturday (value 7) and add 2 days if true.
* **1 Mark**: Correct condition/logic to check for Sunday (value 1) and add 1 day if true.
* **1 Mark**: Correct re-evaluation of the weekday index (either by re-calling `DAYOFWEEK(TargetDate)` or setting the index logically to 2/Monday) after adjustments.
* **1 Mark**: Correct retrieval of the string name from the `WeekdayNames` array using the computed weekday index.
* **1 Mark**: Correct string concatenation to combine the weekday name, `", "`, and the result of `GETDATESTRING(TargetDate)`, and returning the correct string with `ENDFUNCTION` terminated properly.
題目 3 · structural_and_algorithm_design
10
A circular queue is implemented as a 1D array Queue[1:5] of strings, with two integer pointers, HeadPointer and TailPointer, and an integer variable NumItems that stores the current number of items in the queue.

Initially, the queue is empty with HeadPointer = 1, TailPointer = 0, and NumItems = 0.

The operations to manage the queue are defined as follows:
- Enqueue: TailPointer is incremented. If it exceeds 5, it wraps around to 1. The item is stored at Queue[TailPointer] and NumItems is incremented by 1.
- Dequeue: The item at Queue[HeadPointer] is retrieved. HeadPointer is then incremented. If it exceeds 5, it wraps around to 1, and NumItems is decremented by 1.

The following sequence of operations is executed:
1. Enqueue "Apple"
2. Enqueue "Banana"
3. Enqueue "Cherry"
4. Dequeue
5. Enqueue "Date"
6. Enqueue "Fig"
7. Enqueue "Grape"
8. Dequeue

(a) State the values of HeadPointer, TailPointer, and NumItems after each of the following operations are completed:
(i) Operation 3 is completed. [1 mark]
(ii) Operation 6 is completed. [1 mark]
(iii) Operation 7 is completed. [1 mark]
(iv) Operation 8 is completed. [1 mark]

(b) Write pseudocode for the procedure SaveQueueToFile(). The procedure must write all active items currently in the queue to a sequential text file "QueueData.txt", one item per line, in the order they would be dequeued (FIFO order). The queue's state and pointers must not be modified. If the queue is empty, the procedure must output "No data to save" and not write to any file. [6 marks]
查看答案詳解

解題

Part (a) Walkthrough:
- Initial State: HeadPointer = 1, TailPointer = 0, NumItems = 0
- Step 1: Enqueue "Apple" → TailPointer = 1, Queue[1] = "Apple", NumItems = 1
- Step 2: Enqueue "Banana" → TailPointer = 2, Queue[2] = "Banana", NumItems = 2
- Step 3: Enqueue "Cherry" → TailPointer = 3, Queue[3] = "Cherry", NumItems = 3. HeadPointer remains 1.
Result (i): HeadPointer = 1, TailPointer = 3, NumItems = 3

- Step 4: Dequeue → HeadPointer increments to 2, NumItems = 2
- Step 5: Enqueue "Date" → TailPointer = 4, Queue[4] = "Date", NumItems = 3
- Step 6: Enqueue "Fig" → TailPointer = 5, Queue[5] = "Fig", NumItems = 4
Result (ii): HeadPointer = 2, TailPointer = 5, NumItems = 4

- Step 7: Enqueue "Grape" → TailPointer wraps around to 1, Queue[1] = "Grape", NumItems = 5
Result (iii): HeadPointer = 2, TailPointer = 1, NumItems = 5

- Step 8: Dequeue → HeadPointer increments to 3, NumItems = 4
Result (iv): HeadPointer = 3, TailPointer = 1, NumItems = 4

Part (b) Pseudocode Logic:
To output the elements in order without modifying the global pointers, we copy HeadPointer to a local temporary variable (e.g., CurrentPointer) and iterate a number of times equal to NumItems. In each iteration, we write Queue[CurrentPointer] and then increment CurrentPointer, resetting it to 1 if it exceeds the boundary (5).

評分準則

Part (a) [4 Marks]:
- (i) 1 mark for: HeadPointer = 1, TailPointer = 3, NumItems = 3
- (ii) 1 mark for: HeadPointer = 2, TailPointer = 5, NumItems = 4
- (iii) 1 mark for: HeadPointer = 2, TailPointer = 1, NumItems = 5
- (iv) 1 mark for: HeadPointer = 3, TailPointer = 1, NumItems = 4

Part (b) [6 Marks]:
- 1 mark: Check if queue is empty (NumItems = 0) and output "No data to save" if so.
- 1 mark: Open "QueueData.txt" for WRITE (and CLOSEFILE at the end).
- 1 mark: Initialise a temporary pointer/index variable to HeadPointer.
- 1 mark: Set up a loop that runs exactly NumItems times (e.g. FOR Count ← 1 TO NumItems).
- 1 mark: Write the element at the temporary index (Queue[CurrentPointer]) to the file inside the loop.
- 1 mark: Increment the temporary index and handle the circular wrap-around logic correctly (if > 5 then 1).
題目 4 · written
6
A programmer is writing a program that processes text files. As part of this, they need a reusable function to perform single-character matching within a string.

Write pseudocode for the function `CountChar`, which takes two strings as parameters: `TextStr` and `SearchChar`.

The function must perform the following actions:
1. Verify that `SearchChar` has a length of exactly 1. If it does not, the function must immediately return -1.
2. Verify that `TextStr` is not empty. If it is empty, the function must immediately return -1.
3. Count how many times `SearchChar` occurs in `TextStr`. The matching algorithm must be case-insensitive (e.g., 'a' matches both 'a' and 'A').
4. Return the total count of matches.

You must use the following pseudocode built-in functions in your solution:
- `LENGTH(StringVal : STRING) RETURNS INTEGER` which returns the number of characters in `StringVal`.
- `MID(StringVal : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING` which returns a substring of length `Length` starting at position `Start`.
- `UCASE(StringVal : STRING) RETURNS STRING` which returns the uppercase version of `StringVal`.
查看答案詳解

解題

The solution involves writing a complete function according to the pseudocode guide specifications:

1. **Function Definition**: We declare `FUNCTION CountChar(TextStr : STRING, SearchChar : STRING) RETURNS INTEGER` and define local variables using `DECLARE`.
2. **Validation**: We use `LENGTH` to check if `SearchChar` does not have length 1, or if `TextStr` has a length of 0. If either condition is met, we return -1 immediately.
3. **Looping**: We set up a `FOR` loop running from index 1 to `LENGTH(TextStr)` to iterate through every character in the main string.
4. **Extraction**: Inside the loop, `MID(TextStr, Index, 1)` extracts exactly one character at the current index.
5. **Comparison**: By applying `UCASE` to both `CurrentChar` and `SearchChar`, we normalize their cases so that a case-insensitive match can be evaluated.
6. **Return**: Increment the counter if they match, and finally return the counter after the loop completes.

評分準則

Award up to 6 marks for the following:
1. **Function Header & End**: Correct keyword `FUNCTION`, name, parameter names with correct data types, return type (`RETURNS INTEGER`), and matching `ENDFUNCTION`.
2. **Validation**: Correctly checks if `LENGTH(SearchChar) <> 1` and `LENGTH(TextStr) = 0` (or `< 1`), returning `-1` if true.
3. **Variable Initialization**: Correctly declares and initializes `Count` to 0 before the loop.
4. **Loop Design**: A loop that starts at index 1 and correctly runs exactly to `LENGTH(TextStr)`.
5. **Character Extraction**: Correctly extracts the current single character using `MID(TextStr, Index, 1)` inside the loop.
6. **Case-Insensitive Match**: Correctly converts both extracted character and target character to uppercase (or lowercase) using `UCASE` (or `LCASE`), increments `Count` when they match, and returns `Count` at the end.
題目 5 · structural
8
Consider the following pseudocode program: | 01 DECLARE CurrentBalance : REAL | 02 CurrentBalance <- 500.00 | 03 | 04 PROCEDURE ProcessWithdrawal(BYVAL Balance : REAL, BYVAL Amount : REAL) | 05 // Deducts the withdrawal amount from the balance if sufficient funds exist | 06 IF Amount <= Balance THEN | 07 Balance <- Balance - Amount | 08 ELSE | 09 OUTPUT "Insufficient funds" | 10 ENDIF | 11 ENDPROCEDURE | 12 | 13 CALL ProcessWithdrawal(CurrentBalance, 100.00) | 14 OUTPUT "New Balance: ", CurrentBalance | | (a) Identify the parameter passing mode used for Balance in line 04 that causes the logic bug, and explain why this mode prevents the program from updating CurrentBalance correctly. (3 marks) | (b) Write the corrected version of line 04 to resolve this logic bug. (1 mark) | (c) State the scope of the formal parameter Balance. Explain what would occur if a variable named CurrentBalance was declared locally inside the ProcessWithdrawal procedure. (2 marks) | (d) Explain how the inline comment on line 05 assists in the maintenance of this program. (2 marks)
查看答案詳解

解題

Part (a): The code currently uses BYVAL for the Balance parameter. Passing by value creates a local copy. When the subtraction occurs, only the copy is updated, leaving CurrentBalance at 500.00. To fix this, BYREF (By Reference) must be used. | Part (b): Changing BYVAL to BYREF for the Balance parameter allows the procedure to reference the memory address of the argument passed, modifying CurrentBalance directly. | Part (c): Formal parameters always have a local scope. Local declaration of an identifier with the same name as a global variable overrides the global variable's visibility within that scope (shadowing). | Part (d): Program maintenance requires understanding program design. Inline comments explain 'what' the code intends to do, which is critical if the code contains a logic bug (the 'how' is incorrect).

評分準則

Part (a) [Max 3 marks]: | - 1 mark: Identifies parameter passing mode as BYVAL / By Value. | - 1 mark: Explains that BYVAL passes a copy of the data/value to the procedure. | - 1 mark: Explains that modifications only affect the local copy, leaving the original argument (CurrentBalance) unchanged. | Part (b) [Max 1 mark]: | - 1 mark: Correctly rewrites line 04 with BYREF for Balance (e.g., PROCEDURE ProcessWithdrawal(BYREF Balance : REAL, BYVAL Amount : REAL)). | Part (c) [Max 2 marks]: | - 1 mark: Identifies the scope of Balance as local. | - 1 mark: Explains that a local CurrentBalance variable would shadow/mask the global variable (making it inaccessible inside the procedure). | Part (d) [Max 2 marks]: | - 1 mark: Mentions that the comment documents the purpose/intent of the code block. | - 1 mark: Explains that this saves time for future developers / makes it easier to identify logic bugs during maintenance.
題目 6 · coding
6
A programmer wants to write a procedure `PrintPattern(N : INTEGER)` to output a square pattern of size \(N \times N\) using characters.

The pattern must consist of:
- A border of '*' characters (representing the first and last rows, and the first and last columns).
- A diagonal of '*' characters running from the top-left corner to the bottom-right corner.
- Spaces (' ') in all other positions.

For example, if `N` is 5, the output should be:
```text
*****
** *
* * *
* **
*****
```

You must assume that:
- \(N\) is an integer greater than or equal to 3.
- The pseudocode statement `WRITE ` outputs a value on the same line (without a newline).
- The pseudocode statement `OUTPUT ""` outputs a newline character.

Write pseudocode for the procedure `PrintPattern(N : INTEGER)`.
查看答案詳解

解題

To solve this problem, we need to print a 2D grid of size \(N \times N\). This requires a nested loop structure: an outer loop iterating through each row (`Row` from 1 to `N`), and an inner loop iterating through each column in that row (`Col` from 1 to `N`).

For each position `(Row, Col)`:
1. We check if it is part of the border. This is true if:
- It is the first row: `Row = 1`
- It is the last row: `Row = N`
- It is the first column: `Col = 1`
- It is the last column: `Col = N`
2. We check if it is part of the leading diagonal. This is true if:
- `Row = Col`

If any of these conditions are true, we output `*` using the `WRITE` statement.
Otherwise, we output a space `' '`.

After printing all the columns for a single row (i.e., after the inner loop completes), we must move to the next line by printing a newline using `OUTPUT ""` before the outer loop advances to the next row.

評分準則

1 mark: Correct procedure header (with parameter `N : INTEGER`) and matching `ENDPROCEDURE`.
1 mark: Outer loop structure running from 1 to `N` (or 0 to `N - 1`).
1 mark: Inner loop structure running from 1 to `N` (or 0 to `N - 1`).
1 mark: Correct conditions for the border check (`Row = 1 OR Row = N OR Col = 1 OR Col = N` or equivalent indices).
1 mark: Correct condition for the diagonal check (`Row = Col`) combined correctly using `OR` with the border check.
1 mark: Correct outputs: writing `*` and space character appropriately, and printing a newline (`OUTPUT ""`) at the end of each row (after the inner loop but inside the outer loop).
題目 7 · 結構題
9

A smart parcel delivery locker system, "LockerBox", is installed in a residential apartment lobby. The system allows delivery drivers to deposit parcels and residents to retrieve them. The system uses a keypad for PIN entry and a weight sensor inside the locker to detect if a parcel has been deposited.

Part (a)

The software for the LockerBox system is designed using modular programming. Separate modules are designed for collecting weight sensor data, collecting keypad inputs, and communicating with the central database to verify PINs.

Explain three advantages of using modular programming to design and implement this information collection system.


Part (b)

The state transition table below tracks the state of a single LockerBox compartment. Complete the state transition table by identifying the missing entries represented by labels [A], [B], [C], [D], [E], and [F].


Current StateEventNext StateActionLocked_Empty"Deliver" button pressedAwaiting_PINPrompt for PINAwaiting_PINCorrect PIN entered[A]Unlock doorAwaiting_PIN[B]Locked_EmptyDisplay errorUnlockedDoor closed and weight detectedLocked_Full[C]UnlockedDoor closed and weight NOT detected[D]Lock doorLocked_FullCorrect Retrieval PIN enteredUnlocked[E][F]Door closed and weight NOT detected (after retrieval)Locked_EmptyLock door
查看答案詳解

解題

Part (a) Justification (Max 3 marks):

  • Code Reusability: Designing information collection as distinct modules (such as input reading) means these routines can be reused across different physical interfaces or future locker models without rewriting code.
  • Parallel Development: Team members can work independently on separate aspects. One developer can implement the physical integration of the weight sensor module while another builds the network-reliant database validation module.
  • Easier Debugging / Maintenance: Isolating tasks makes it easier to locate errors. If a sensor reports faulty readings, developers only need to check and test the weight collection module, which minimizes the risk of introducing bugs to the user interface.

Part (b) State Transition Table Completion (6 marks):

  • [A]: When in state Awaiting_PIN and a correct PIN is successfully entered, the locker changes its physical status to Unlocked to allow access.
  • [B]: To transition from Awaiting_PIN back to Locked_Empty, the event must be an invalid attempt, such as "Incorrect PIN entered" or "Timeout".
  • [C]: When a user closes the door and weight is detected (indicating a parcel is inside), the physical lock must be engaged. Therefore, the action is "Lock door".
  • [D]: If the door is closed and no weight is detected, the locker remains empty, reverting to the Locked_Empty state.
  • [E]: To allow retrieval, the action triggered by entering a valid retrieval PIN is to "Unlock door".
  • [F]: The customer has retrieved the parcel, meaning the locker was Unlocked. Closing the door when empty transitions it back to Locked_Empty, meaning the starting state for this row was Unlocked.

評分準則

Part (a) [Total: 3 marks]

  • 1 mark for each valid, distinct point of justification applied to the LockerBox context (up to 3 marks).
  • Acceptable points: Easier to debug/isolate faults, allows parallel development/specialisation of programmers, code reusability of independent input modules, simplified maintenance when physical hardware interfaces change.

Part (b) [Total: 6 marks]

  • [A]: 1 mark for Unlocked (Accept: Unlocked_Empty)
  • [B]: 1 mark for Incorrect PIN entered (Accept: Incorrect PIN / Three incorrect PINs / Timeout)
  • [C]: 1 mark for Lock door (Accept: Lock locker)
  • [D]: 1 mark for Locked_Empty (Accept: Locked_Empty state)
  • [E]: 1 mark for Unlock door (Accept: Release lock)
  • [F]: 1 mark for Unlocked (Accept: Unlocked_Occupied)
題目 8 · practical
17
A school system manages student records. The records are stored in a sequential file StudentMaster.txt sorted in ascending order of StudentID. Another sorted sequential file StudentUpdates.txt contains update records.

A user-defined type StudentRecord is defined as follows:

TYPE StudentRecord
DECLARE StudentID : STRING
DECLARE StudentName : STRING
DECLARE Status : CHAR
ENDTYPE

(a) Write pseudocode for a function IsValid(Record : StudentRecord) RETURNS BOOLEAN. The function validates the student record according to the following rules:
1. The StudentID must be exactly 6 characters long.
2. Each character in the StudentID must be a numeric digit ('0' to '9').
3. The Status must be either 'A' (Active) or 'S' (Suspended).

If all validation rules are met, the function returns TRUE, otherwise it returns FALSE. [5 marks]

(b) Write pseudocode for the procedure MergeFiles(). This procedure merges records from StudentMaster.txt and StudentUpdates.txt into a new file NewStudentMaster.txt in ascending order of StudentID.

Your procedure must implement the following logic:
- Open all files.
- Read records sequentially from StudentMaster.txt and StudentUpdates.txt.
- If an update record has a StudentID that does not exist in the master file:
- If the update record is valid, write it to NewStudentMaster.txt.
- If the update record is invalid, write the StudentID and an error message (e.g., "StudentID - Invalid Record") to ErrorLog.txt.
- If an update record has a StudentID that matches a record in the master file:
- If the update record is valid, write the update record to NewStudentMaster.txt (replacing the old master record).
- If the update record is invalid, write the original master record to NewStudentMaster.txt and write the StudentID and an error message to ErrorLog.txt.
- Write any remaining records to NewStudentMaster.txt (with remaining update records validated appropriately).
- Close all files.

Use standard CAIE pseudocode files operations (e.g., OPENFILE, READFILE, WRITEFILE, CLOSEFILE, EOF). [12 marks]
查看答案詳解

解題

(a) Pseudocode for IsValid function:

FUNCTION IsValid(Record : StudentRecord) RETURNS BOOLEAN
DECLARE IDLength : INTEGER
DECLARE Index : INTEGER
DECLARE Digit : CHAR

IDLength <- LENGTH(Record.StudentID)
IF IDLength <> 6 THEN
RETURN FALSE
ENDIF

FOR Index <- 1 TO 6
Digit <- MID(Record.StudentID, Index, 1)
IF Digit < "0" OR Digit > "9" THEN
RETURN FALSE
ENDIF
NEXT Index

IF Record.Status <> 'A' AND Record.Status <> 'S' THEN
RETURN FALSE
ENDIF

RETURN TRUE
ENDFUNCTION

(b) Pseudocode for MergeFiles procedure:

PROCEDURE MergeFiles()
DECLARE MasterRec : StudentRecord
DECLARE UpdateRec : StudentRecord
DECLARE MasterEOF : BOOLEAN
DECLARE UpdateEOF : BOOLEAN

OPENFILE "StudentMaster.txt" FOR READ
OPENFILE "StudentUpdates.txt" FOR READ
OPENFILE "NewStudentMaster.txt" FOR WRITE
OPENFILE "ErrorLog.txt" FOR WRITE

MasterEOF <- FALSE
UpdateEOF <- FALSE

IF NOT EOF("StudentMaster.txt") THEN
READFILE "StudentMaster.txt", MasterRec
ELSE
MasterEOF <- TRUE
ENDIF

IF NOT EOF("StudentUpdates.txt") THEN
READFILE "StudentUpdates.txt", UpdateRec
ELSE
UpdateEOF <- TRUE
ENDIF

WHILE MasterEOF = FALSE AND UpdateEOF = FALSE
IF MasterRec.StudentID < UpdateRec.StudentID THEN
WRITEFILE "NewStudentMaster.txt", MasterRec
IF NOT EOF("StudentMaster.txt") THEN
READFILE "StudentMaster.txt", MasterRec
ELSE
MasterEOF <- TRUE
ENDIF
ELSE
IF MasterRec.StudentID > UpdateRec.StudentID THEN
IF IsValid(UpdateRec) = TRUE THEN
WRITEFILE "NewStudentMaster.txt", UpdateRec
ELSE
WRITEFILE "ErrorLog.txt", UpdateRec.StudentID & " - Invalid Record"
ENDIF
IF NOT EOF("StudentUpdates.txt") THEN
READFILE "StudentUpdates.txt", UpdateRec
ELSE
UpdateEOF <- TRUE
ENDIF
ELSE
// Keys are equal
IF IsValid(UpdateRec) = TRUE THEN
WRITEFILE "NewStudentMaster.txt", UpdateRec
ELSE
WRITEFILE "NewStudentMaster.txt", MasterRec
WRITEFILE "ErrorLog.txt", UpdateRec.StudentID & " - Invalid Update"
ENDIF

IF NOT EOF("StudentMaster.txt") THEN
READFILE "StudentMaster.txt", MasterRec
ELSE
MasterEOF <- TRUE
ENDIF

IF NOT EOF("StudentUpdates.txt") THEN
READFILE "StudentUpdates.txt", UpdateRec
ELSE
UpdateEOF <- TRUE
ENDIF
ENDIF
ENDIF
ENDWHILE

WHILE MasterEOF = FALSE
WRITEFILE "NewStudentMaster.txt", MasterRec
IF NOT EOF("StudentMaster.txt") THEN
READFILE "StudentMaster.txt", MasterRec
ELSE
MasterEOF <- TRUE
ENDIF
ENDWHILE

WHILE UpdateEOF = FALSE
IF IsValid(UpdateRec) = TRUE THEN
WRITEFILE "NewStudentMaster.txt", UpdateRec
ELSE
WRITEFILE "ErrorLog.txt", UpdateRec.StudentID & " - Invalid Record"
ENDIF
IF NOT EOF("StudentUpdates.txt") THEN
READFILE "StudentUpdates.txt", UpdateRec
ELSE
UpdateEOF <- TRUE
ENDIF
ENDWHILE

CLOSEFILE "StudentMaster.txt"
CLOSEFILE "StudentUpdates.txt"
CLOSEFILE "NewStudentMaster.txt"
CLOSEFILE "ErrorLog.txt"
ENDPROCEDURE

評分準則

Part (a) Marking Scheme (Max 5 marks):
- 1 mark: Correct function header with parameter and return type, and corresponding ENDFUNCTION.
- 1 mark: Validates length of StudentID is exactly 6.
- 1 mark: Uses a loop to iterate through each character of StudentID.
- 1 mark: Checks if each character is a digit between '0' and '9'.
- 1 mark: Validates Status is 'A' or 'S' and returns TRUE/FALSE correctly.

Part (b) Marking Scheme (Max 12 marks):
- 1 mark: Opens all 4 files with correct modes and closes them at the end.
- 1 mark: Initialises EOF flags and reads the first record from both files correctly.
- 1 mark: Correct loop structure while both files have records remaining.
- 1 mark: Correct comparison and action when Master ID < Update ID.
- 1 mark: Correct comparison when Master ID > Update ID, calling IsValid() on the update record.
- 1 mark: In Master ID > Update ID case, writes valid record to NewStudentMaster.txt or logs invalid record to ErrorLog.txt.
- 1 mark: Correct logic when Master ID = Update ID, calling IsValid() on the update record.
- 1 mark: In Master ID = Update ID case, writes valid update record, or keeps master record and logs invalid update error.
- 1 mark: Correctly updates file pointers (reading next record) for both files inside the main loop conditions.
- 1 mark: Correct loop to copy remaining master records.
- 1 mark: Correct loop to process remaining update records (must include IsValid check).
- 1 mark: Avoids syntax/logical errors, maintaining correct EOF updates to prevent infinite loops.

想知道自己有幾分把握?

Thinka 是 DSE 學生用的 AI 練習應用程式,有無限量練習題、即時自動批改和詳細解題步驟。逾 100,000 名學生用它確認自己真的識,而不只是「以為識」。

想練更多類似題型?在 Thinka 無限量操練,即時知道答案。

免費開始練習