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

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

Thinka Nov 2025 (V1) Cambridge International A Level-Style Mock — Computer Science (9618)

150 210 分鐘2025
An original Thinka practice paper modelled on the structure and difficulty of the Nov 2025 (V1) Cambridge International A Level Computer Science (9618) paper. Not affiliated with or reproduced from Cambridge.

Paper 11 - Theory Fundamentals

Answer all questions. Calculators must not be used. Write all your answers in the spaces provided.
32 題目 · 77
題目 1 · Short Answer
2.5
Describe how the sampling rate and sampling resolution of an analogue-to-digital converter (ADC) affect both the sound accuracy and the final file size of a digital recording.
查看答案詳解

解題

Sampling rate determines how many samples of the analogue sound wave are taken per second. A higher sampling rate means the digital representation matches the original analogue signal more closely, reducing distortion. Sampling resolution (or bit depth) is the number of bits used to encode each sample. A higher sampling resolution allows for more precise amplitude measurements, reducing quantization noise. However, increasing either parameter increases the number of bits stored per second, which proportionally increases the final audio file size.

評分準則

1 mark: Higher sampling rate captures the analogue wave more frequently, increasing fidelity / accuracy to the original sound wave. 1 mark: Higher sampling resolution allows more discrete amplitude levels, reducing quantization error/noise. 0.5 mark: Higher values for either parameter mean more bits must be stored per second of audio, resulting in a larger file size.
題目 2 · Short Answer
2.5
Explain two distinct advantages of executing validation scripts on the client-side (inside the user's web browser) rather than sending the data to the server for validation.
查看答案詳解

解題

Client-side scripting validates data locally before it is transmitted. This provides immediate feedback to the user without waiting for a server round-trip, improving user experience. It also prevents invalid data from being transmitted over the network, reducing network traffic and offloading processing work from the web server, which improves server scalability.

評分準則

1 mark: Immediate feedback / faster response time for the user, as the validation occurs instantly without waiting for network transmission. 1 mark: Reduces web server load, as invalid data is filtered out before reaching the server, saving processing power. 0.5 mark: Reduces network bandwidth/congestion because rejected forms do not need to be transmitted.
題目 3 · Short Answer
2.5
Describe how a resistive touchscreen detects a touch event, and state one disadvantage of a resistive touchscreen compared to a capacitive touchscreen.
查看答案詳解

解題

A resistive touchscreen consists of two thin, conductive, flexible layers separated by a small gap or spacer dots. When a user presses the screen, the top flexible layer bends and makes physical contact with the bottom layer. This contact completes an electrical circuit, altering the resistance and causing a change in electrical current. The touchscreen controller calculates the exact coordinates based on the voltage change. A disadvantage is that they generally do not support multi-touch gestures (like pinching) and have lower clarity/sensitivity to light touch compared to capacitive screens.

評分準則

1 mark: Pressing the screen forces two conductive/resistive layers to make physical contact, completing an electrical circuit. 1 mark: The controller measures the change in electrical current/voltage to determine the coordinates of the touch point. 0.5 mark: Disadvantage: Poor/no multi-touch support, lower screen visibility in bright light, or less responsive to very light finger touch (requires physical pressure).
題目 4 · Short Answer
2.5
State the purpose of a disk defragmenter utility and explain how it improves the read/write performance of a magnetic hard disk drive (HDD).
查看答案詳解

解題

As files are created, modified, and deleted, they become fragmented and scattered across non-contiguous sectors of a magnetic hard disk. A disk defragmenter utility reorganizes these file blocks so that all sectors of each individual file are stored in contiguous (consecutive) sectors. This improves performance because the physical read/write head does not have to move across multiple tracks and sectors to access different parts of the same file, reducing seek time and disk wear.

評分準則

1 mark: Reorganizes fragmented sectors of files on the disk so that each file's data blocks are stored contiguously (consecutively). 1 mark: Consolidates free space into one large continuous block. 0.5 mark: Minimizes physical movement of the read/write head, significantly reducing file seek/access times.
題目 5 · Short Answer
2.5
Distinguish between data validation and data verification, and state one specific validation check that could be performed on a user's date of birth input.
查看答案詳解

解題

Data validation is an automated check performed by software to ensure that input data is reasonable, sensible, and complies with predefined rules before processing. Data verification is a process used to ensure that the data has been copied or transferred accurately from the source document to the computer without error. A valid check for a date of birth input is a range check (to ensure the year is between a reasonable minimum and maximum, e.g., 1900 and the current year) or a format check (DD/MM/YYYY).

評分準則

1 mark: Validation is an automatic computer check to ensure data is sensible/logical/conforms to constraints. 1 mark: Verification ensures that the entered data is an exact copy of the source data (e.g., through double entry or visual check). 0.5 mark: Appropriate validation check example (e.g., Range check on the year, Format check, or Presence check).
題目 6 · Short Answer
2.5
Explain the roles of the Program Counter (PC) and the Memory Address Register (MAR) during the fetch stage of the Fetch-Execute cycle.
查看答案詳解

解題

At the start of the fetch stage, the Program Counter (PC) holds the memory address of the next instruction to be fetched and executed. This address is copied from the PC to the Memory Address Register (MAR) via the system's address bus. Once the MAR has the address, the PC is incremented to point to the next instruction in sequence, while the MAR coordinates with memory to retrieve the actual instruction.

評分準則

1 mark: The Program Counter (PC) stores the address of the next instruction to be fetched. 1 mark: The address from the PC is copied directly into the Memory Address Register (MAR). 0.5 mark: The PC is incremented to point to the subsequent instruction address.
題目 7 · Short Answer
2.5
Define the term 'foreign key' in a relational database, and explain how it is used to maintain referential integrity between two tables.
查看答案詳解

解題

A foreign key is an attribute (or collection of attributes) in a database table that refers to, and matches, the primary key of another table. It establishes a physical relationship between the two tables. To maintain referential integrity, the database management system (DBMS) ensures that any value entered into the foreign key column must already exist in the primary key column of the referenced table. This prevents 'orphaned' records and ensures consistent relationships.

評分準則

1 mark: Definition: An attribute or set of attributes in one table that links to the primary key of another table. 1 mark: Referential Integrity: Ensures that no foreign key value can exist without a corresponding primary key value in the parent table. 0.5 mark: Prevents users from deleting a primary key record if linked foreign key records still depend on it (or cascading must occur).
題目 8 · Short Answer
2.5
State two benefits to a software developer of distributing their software under an open-source license rather than a proprietary license.
查看答案詳解

解題

When a developer releases software under an open-source license, other programmers worldwide can view, modify, and improve the source code. This leads to collaborative development, where bugs are found and fixed faster, and new features are added without the original developer doing all the work. Additionally, it increases software adoption, builds developer reputation, and allows integrating standard community-maintained libraries.

評分準則

1 mark: Benefit 1: Allows community collaboration, meaning other developers can submit bug fixes, improvements, and new features. 1 mark: Benefit 2: Faster development cycles and robust security auditing, as the source code is public and reviewed by many peers. 0.5 mark: Benefit 3: Increases wider adoption and usage of the software as it is free of licensing costs, raising the developer's reputation.
題目 9 · Short Answer
2.5
Show how the denary value \(-75\) is represented as an 8-bit two's complement integer. Show your working.
查看答案詳解

解題

1. Convert the absolute denary value 75 to an unsigned 8-bit binary representation: \(75 = 64 + 8 + 2 + 1\), which is \(01001011_{2}\). 2. Find the one's complement by inverting all of the bits: \(10110100_{2}\). 3. Find the two's complement by adding 1 to the result: \(10110100_{2} + 1 = 10110101_{2}\). Alternatively, using the binary weightings method: \(-128 + 32 + 16 + 4 + 1 = -75\), which corresponds to placing 1s at weights -128, 32, 16, 4, and 1, yielding \(10110101_{2}\).

評分準則

1 mark: Correct binary representation of the positive value (+75) as 01001011. 1 mark: Showing a valid method for conversion (such as bit inversion followed by adding 1, or correct placement of column weightings including -128). 0.5 marks: Correct final 8-bit binary answer (10110101).
題目 10 · Short Answer
2.5
Identify the register in the Von Neumann CPU architecture that holds the address of the next instruction to be fetched, and describe its role during the fetch stage of the Fetch-Execute cycle.
查看答案詳解

解題

The register is the Program Counter (PC). During the fetch stage of the Fetch-Execute cycle, the memory address stored in the PC is copied to the Memory Address Register (MAR) over the address bus. Immediately after this transfer, the Program Counter is incremented by 1 so that it points to the memory address of the next sequential instruction to be fetched.

評分準則

1 mark: Identifying the register as the Program Counter (PC). 1 mark: Explaining that its address value is copied to the Memory Address Register (MAR) at the start of the fetch stage. 0.5 marks: Stating that the Program Counter is then incremented (by 1) to point to the next instruction.
題目 11 · Short Answer
2.5
Compare a Media Access Control (MAC) address with an Internet Protocol (IP) address, highlighting two distinct differences in their characteristics or usage.
查看答案詳解

解題

1. Allocation/Permanence: A MAC address is a hardware-level physical address that is permanently burned into the Network Interface Card (NIC) by the manufacturer and cannot be changed. In contrast, an IP address is a logical network address assigned to a device dynamically or statically by a network administrator or DHCP server, which can change depending on the network the device connects to. 2. Role in Routing: A MAC address is primarily used to identify devices and route frames within the local area network (at the Data Link Layer), whereas an IP address is used to route packets across different subnets or the wider internet (at the Network Layer).

評分準則

1 mark: Describing the difference in permanence and assignment (MAC is physical, static, and hardcoded by the manufacturer; IP is logical, dynamic/static, and assigned by a network/DHCP). 1 mark: Describing the difference in scope of transmission (MAC is used for local data routing within the same network; IP is used for global routing across different networks). 0.5 marks: Providing structural details (e.g., MAC is 48/64 bits in hexadecimal format; IPv4 is 32 bits in dotted decimal format).
題目 12 · Short Answer
2.5
An automated system controls the temperature of a commercial greenhouse. State the type of sensor required to monitor the environment, and explain how an actuator is used to reduce the temperature if it exceeds a set threshold.
查看答案詳解

解題

The system utilizes a temperature sensor to monitor the greenhouse temperature. The analogue signals from the sensor are converted to digital and read by a microcontroller. If the microcontroller detects that the temperature has exceeded the threshold, it sends a digital control signal (often amplified or converted) to an actuator, such as an electric motor. The actuator converts this signal into mechanical action to open a motorized ventilation hatch or turn on a cooling fan, lowering the greenhouse temperature.

評分準則

1 mark: Correctly identifying the temperature sensor. 1 mark: Explaining that the microcontroller evaluates the reading and sends a control signal to the actuator when the threshold is exceeded. 0.5 marks: Explaining that the actuator executes physical movement/action (e.g., turning on a fan or opening a window) to reduce temperature.
題目 13 · Short Answer
2.5
Explain the purpose of a disk defragmenter utility program and how its operation improves the performance of a Hard Disk Drive (HDD).
查看答案詳解

解題

Over time, files stored on a Hard Disk Drive (HDD) become fragmented, with parts of a single file scattered across non-contiguous sectors. A disk defragmenter reorganizes these file fragments so that the data blocks for each file are stored next to each other in contiguous sectors. It also pools the free space. This improves HDD performance because the mechanical read/write head does not have to move across multiple tracks and sectors to retrieve a single file, thereby minimizing seek time and overall read/write latency.

評分準則

1 mark: Explaining that the defragmenter reorganizes scattered/fragmented files into contiguous (consecutive) sectors. 1 mark: Stating that it consolidates free space to prevent future fragmentation. 0.5 marks: Explaining the performance benefit: reduces movement of the mechanical read/write head, lowering seek time and increasing data retrieval speeds (Note: do not accept speed improvements for SSDs, as this is specific to HDDs).
題目 14 · Short Answer
2.5
Contrast commercial (proprietary) software licenses with free software (open-source) licenses in terms of access to the source code and the right to modify the software.
查看答案詳解

解題

1. Source Code Access: Commercial (proprietary) software licenses do not provide the user with access to the source code; the software is distributed in compiled executable format. Open-source licenses make the source code freely available to all users. 2. Modification Rights: Commercial licenses legally restrict users from modifying, adapting, or reverse-engineering the software. Open-source licenses grant users the legal right to modify and adapt the source code to suit their specific requirements.

評分準則

1 mark: Contrasting source code access (proprietary restricts access / code is closed, while open-source provides open access to the code). 1 mark: Contrasting modification rights (proprietary legally forbids modification, while open-source explicitly permits and encourages modification). 0.5 marks: Clarity of comparison and use of appropriate technical terminology.
題目 15 · Short Answer
2.5
In a relational database, explain how a primary key and a foreign key work together to establish a relationship between two tables, and state how referential integrity is maintained.
查看答案詳解

解題

A primary key is an attribute that uniquely identifies each record in a 'parent' table. To establish a relationship, this primary key is added as an attribute (known as a foreign key) in a related 'child' table. Referential integrity is maintained by database management rules which ensure that a value cannot be entered in the foreign key field of the child table unless it already exists in the primary key field of the parent table. It also prevents the deletion of a parent record if there are child records referencing it.

評分準則

1 mark: Explaining the relationship structure (primary key uniquely identifies a row in one table, and is placed as a foreign key in another table to link them). 1 mark: Explaining the core rule of referential integrity (any value in the foreign key field must match an existing primary key value in the related table, or be null). 0.5 marks: Describing the consequence of maintaining referential integrity (e.g., prevents orphaned records or invalid links when deleting/updating records).
題目 16 · Short Answer
2.5
Distinguish between data validation and data verification during data entry, providing an example of a technique used for each.
查看答案詳解

解題

Data validation is an automated check performed by the computer to ensure that entered data is sensible, reasonable, and conforms to a set of predefined rules (e.g., a range check ensuring an age is between 0 and 120). Data verification is a process used to check whether the entered data matches the source data exactly, to ensure no transcription or transmission errors occurred (e.g., double entry, where data is keyed in twice by different users and compared for differences).

評分準則

1 mark: Explaining validation as an automated rule-based sensibility check, with a correct example (e.g., range check, length check, type check). 1 mark: Explaining verification as a check for accuracy against original source data, with a correct example (e.g., double entry, visual check/proofreading). 0.5 marks: Correctly contrasting their different goals (validation ensures compliance with data rules; verification ensures correctness against the source data).
題目 17 · Short Answer
2.5
Explain why Binary Coded Decimal (BCD) representation is used in devices like digital clocks and electronic calculators instead of pure binary. In your answer, identify one disadvantage of BCD representation compared to pure binary.
查看答案詳解

解題

1. BCD represents each decimal digit separately using a fixed 4-bit binary code. This avoids conversion errors and makes the translation from internal representation to a 7-segment display direct and straightforward.
2. In pure binary, representing fractional or decimal numbers can lead to rounding errors, and converting binary values back to decimal digits for displays requires complex division operations.
3. Disadvantage: BCD is highly inefficient in terms of storage capacity. Since a 4-bit nibble can represent 16 values, but BCD only uses 10 (0 to 9), the remaining 6 states are wasted.

評分準則

• 1 mark: Explain that BCD maps each decimal digit directly to a 4-bit representation, making display decoding (e.g., on 7-segment displays) simple and direct.
• 1 mark: Explain that BCD avoids rounding or precision errors that can occur during conversion of decimal fractions to binary.
• 0.5 marks: Identify a valid disadvantage (e.g., inefficient memory/storage usage since 6 binary states out of 16 are unused; or arithmetic operations are more complex/slower to implement in hardware).
題目 18 · Short Answer
2.5
An automated ventilation system in an industrial greenhouse monitors and regulates temperature. Describe the role of a temperature sensor and an actuator within this closed-loop feedback system.
查看答案詳解

解題

In a closed-loop system:
1. Sensor: The temperature sensor continuously monitors physical environment conditions, taking analog readings of the temperature. It converts these readings into digital signals (using an ADC) so that they can be read and compared against preset target values by the microprocessor.
2. Actuator: The actuator is the output device that performs physical movement or control. When the microprocessor determines that the temperature is outside the threshold, it sends a control signal to the actuator (e.g., an electric motor or heating element) to physically open vents or turn on heaters, bringing the temperature back to the set target.

評分準則

• 1 mark: Explain the role of the temperature sensor (sensing/measuring physical temperature, converting analogue signals to digital, and sending them to the microprocessor/controller).
• 1 mark: Explain the role of the actuator (receiving electrical control signals from the microprocessor and converting them to physical movement/action, e.g., opening a window/starting a motor).
• 0.5 marks: Explicitly describe how they work together in a closed-loop system (microprocessor continuously compares sensor values with a target/threshold to decide if the actuator needs to be triggered).
題目 19 · Short Answer
2.5
In the Von Neumann CPU architecture, during the Instruction Cycle, the Current Instruction Register (CIR) holds the instruction currently being decoded and executed. State the two components into which an instruction is split within the CIR, and describe how these components are processed.
查看答案詳解

解題

An instruction in machine code consists of two main parts when loaded into the CIR:
1. Opcode (Operation Code): This defines the specific instruction or operation to be performed (e.g., ADD, LDM, STO). It is sent to the Control Unit where circuitry decodes it into control signals.
2. Operand: This represents the data that is to be operated on, or more commonly, the address in memory where that data is stored. It is loaded into the MAR to fetch the data, or processed directly if it is an immediate value.

評分準則

• 1 mark: Identify both components: Opcode and Operand (0.5 marks each).
• 1 mark: Explain the processing of the Opcode (sent to the Control Unit, decoded to generate control signals or determine the instruction type).
• 0.5 marks: Explain the processing of the Operand (holds the address of the data or the actual data value, passed to the MAR or Accumulator to be accessed/used during execution).
題目 20 · Short Answer
2.5
The operating system (OS) is responsible for memory management. Identify two functions of the OS during memory management, and explain how virtual memory is utilized when primary memory (RAM) is full.
查看答案詳解

解題

Memory Management Functions:
1. Tracking memory allocation (which parts are in use and by which program).
2. Allocating memory blocks to programs when they load, and freeing (deallocating) them when they terminate.
3. Protecting memory spaces from being overwritten or accessed by other unauthorized processes.

Virtual Memory:
When physical RAM is exhausted, a portion of the hard drive or SSD is designated as virtual memory. The OS divides memory into pages. Inactive pages currently in RAM are written (swapped/paged out) to the virtual memory partition on secondary storage. When those inactive pages are needed again, they are swapped back into RAM, while other inactive pages are swapped out.

評分準則

• 1 mark: Identify two distinct memory management functions (0.5 marks each: e.g., tracking memory allocation, allocating/deallocating space, preventing processes from overwriting each other's memory).
• 1 mark: Explain how virtual memory operates (an area of secondary storage used as an extension of RAM; pages of inactive data are swapped out of RAM to the storage disk).
• 0.5 marks: Explain how the data is brought back (pages are swapped/paged back into physical RAM when required by the CPU).
題目 21 · Short Answer
2.5
Compare a checksum and a parity check as methods of checking for transmission errors. State one scenario where a single parity check will fail to detect an error, but a checksum will succeed.
查看答案詳解

解題

Parity Check vs. Checksum:
1. Parity Check: A single bit (the parity bit) is appended to a unit of data (usually a byte) to ensure that the total number of 1-bits is either even or odd. The receiving device counts the 1s to verify consistency. It is only effective at detecting single-bit errors.
2. Checksum: An algorithm is applied to a block of data to generate a numerical value (the checksum) which is appended to the payload. The receiver applies the same algorithm to the received data and compares the result. It can detect multiple bit errors.
3. Failure Scenario: If two bits in the same byte change state (e.g., two 0s become 1s, or one 0 becomes 1 and one 1 becomes 0), the total parity remains unchanged, so a parity check fails to detect the error. However, the numeric sum of the data block changes, so the checksum value calculated at the receiving end will not match, and the error will be detected.

評分準則

• 1 mark: Describe parity checking (appending a parity bit to make count of 1s even or odd, check by counting 1s).
• 1 mark: Describe checksum checking (applying a mathematical algorithm/addition to a block of bytes to produce a checksum value, recalculated and compared at the receiver).
• 0.5 marks: Identify the failure scenario (even number of bit transitions/transpositions in a byte will preserve parity but alter the checksum value, letting checksum detect it while parity fails).
題目 22 · Short Answer
2.5
Distinguish between Freeware and Free Software (as defined by the Free Software Foundation). Your answer must highlight the fundamental ethical difference between the two terms.
查看答案詳解

解題

1. Freeware: Refers to software that is free of charge to download and use. However, it is closed source (proprietary); the author retains all copyright, and users are not permitted to inspect, modify, or redistribute the source code.
2. Free Software: Defined by the Free Software Foundation (FSF) based on four freedoms (freedom to run, copy, distribute, study, change, and improve). The source code must be made public/available.
3. Ethical Difference: Freeware is a commercial/distribution model focusing on zero cost ('free as in free beer'). Free Software is an ethical concept focusing on user rights and freedom from proprietary control ('free as in free speech').

評分準則

• 1 mark: Define Freeware (distributed free of charge, but proprietary, closed source, copyright retained by creator, modifications/redistribution restricted).
• 1 mark: Define Free Software (grants users the freedom to run, modify, share, and study the software; source code must be openly accessible).
• 0.5 marks: Highlight the ethical distinction (Freeware is about price/cost, whereas Free Software is about freedom/liberty of the user).
題目 23 · written
3.25
A database is used by a school library to manage book loans. The database contains three tables: tblBook, tblStudent, and tblBookLoan. The structure of tblBookLoan is as follows:
- LoanID: integer, primary key
- BookID: text of fixed length 6, foreign key referencing tblBook
- StudentID: text of fixed length 8, foreign key referencing tblStudent
- LoanDate: date

Write an SQL DDL script to create the tblBookLoan table, including all primary key and foreign key constraints.
查看答案詳解

解題

The correct SQL script to define the table structure with correct data types, primary key, and foreign key definitions is:

CREATE TABLE tblBookLoan (
LoanID INT PRIMARY KEY,
BookID CHAR(6),
StudentID CHAR(8),
LoanDate DATE,
FOREIGN KEY (BookID) REFERENCES tblBook(BookID),
FOREIGN KEY (StudentID) REFERENCES tblStudent(StudentID)
);

評分準則

- 1.0 mark: Correct CREATE TABLE statement, with correct field names and appropriate data types (e.g. INT, CHAR(6), CHAR(8), DATE).
- 1.0 mark: Correct definition of LoanID as the PRIMARY KEY.
- 1.0 mark: Correct definition of both FOREIGN KEY constraints referencing the parent tables.
- 0.25 marks: Syntactical accuracy (appropriate commas and closing parenthesis with a semicolon).
題目 24 · written
3.25
A business database contains the following tables:
- tblCustomer (CustomerID, FirstName, LastName, Email)
- tblOrder (OrderID, CustomerID, OrderDate, TotalAmount)

Write an SQL query to display the LastName, FirstName, OrderID, and TotalAmount of all orders that have a TotalAmount greater than 150.00 and were placed on or after '2023-01-01'. The results must be sorted alphabetically by LastName, and then, for customers with the same last name, by TotalAmount in descending order.
查看答案詳解

解題

To retrieve the requested attributes from both tables, an INNER JOIN is required on the common field CustomerID. The conditions are combined using AND in the WHERE clause, and the sorting is achieved with ORDER BY:

SELECT tblCustomer.LastName, tblCustomer.FirstName, tblOrder.OrderID, tblOrder.TotalAmount
FROM tblCustomer
INNER JOIN tblOrder ON tblCustomer.CustomerID = tblOrder.CustomerID
WHERE tblOrder.TotalAmount > 150.00 AND tblOrder.OrderDate >= '2023-01-01'
ORDER BY tblCustomer.LastName ASC, tblOrder.TotalAmount DESC;

評分準則

- 1.0 mark: Correct SELECT clause with specified fields and correct inner join condition on CustomerID.
- 1.0 mark: Correct WHERE clauses matching both the TotalAmount filter (> 150.00) and the OrderDate filter (>= '2023-01-01').
- 1.0 mark: Correct ORDER BY clause specifying LastName ascending followed by TotalAmount descending.
- 0.25 marks: Overall SQL syntax correctness.
題目 25 · written
3.25
An airline booking system uses a database containing two tables with the following structures:
- tblFlight (FlightID, FlightNumber, Origin, Destination, DepartureTime)
- tblBooking (BookingID, CustomerID, FlightID, SeatNumber, PricePaid)

(a) State the type of relationship that exists between tblFlight and tblBooking and justify your choice.
(b) Identify the foreign key in the tblBooking table and explain its purpose in linking the two tables.
查看答案詳解

解題

(a) The relationship is One-to-Many from tblFlight to tblBooking. One flight record can relate to multiple booking records, but a booking is associated with only one specific flight.
(b) FlightID is the foreign key in tblBooking. Its purpose is to link the booking table with the flight table, enforcing referential integrity so that any FlightID entered in tblBooking must already exist in tblFlight.

評分準則

- 1.0 mark: Identifying the relationship as One-to-Many (1:M).
- 0.5 marks: Explaining that one flight can have multiple bookings while each booking relates to only one flight.
- 1.0 mark: Correctly identifying FlightID as the foreign key.
- 0.75 marks: Explaining its role in maintaining referential integrity or preventing mismatched/orphan records.
題目 26 · written
3.25
A retail store database has a table named tblProduct with the following attributes:
- ProductID (Primary Key)
- ProductName
- Category
- Price
- StockLevel

Write two separate SQL DML statements to perform the following actions:
1. Increase the Price of all products in the 'Electronics' category by 10%.
2. Insert a new product with the following details: ProductID is 'P502', ProductName is 'Smart Watch', Category is 'Electronics', Price is 199.99, and StockLevel is 15.
查看答案詳解

解題

Action 1 requires an UPDATE statement targeting specific rows with a WHERE clause:
UPDATE tblProduct SET Price = Price * 1.10 WHERE Category = 'Electronics';

Action 2 requires an INSERT INTO statement to add a new record:
INSERT INTO tblProduct (ProductID, ProductName, Category, Price, StockLevel) VALUES ('P502', 'Smart Watch', 'Electronics', 199.99, 15);

評分準則

- 1.5 marks for Action 1: 1.0 mark for correct UPDATE and SET clauses (e.g. Price = Price * 1.10); 0.5 marks for correct WHERE condition.
- 1.5 marks for Action 2: 1.0 mark for correct INSERT INTO structure with all 5 values; 0.5 marks for using quotes appropriately around string values and not numeric values.
- 0.25 marks for separating statements correctly and ensuring overall DML syntax matches standards.
題目 27 · Logic Circuit Design
2.5
A security system monitoring a safe room produces an alarm signal, \( S = 1 \), under specific conditions. Let:
- \( A \) represent 'Motion detected' (1 = True, 0 = False)
- \( B \) represent 'Door is open' (1 = True, 0 = False)
- \( C \) represent 'Keycard authorization successful' (1 = True, 0 = False)

The alarm \( S \) should trigger (equal 1) if motion is detected AND the keycard authorization was NOT successful, OR if the door is open AND the keycard authorization was NOT successful.

Write the Boolean expression that represents this logic system for \( S \). Do not simplify your expression.
查看答案詳解

解題

To find the Boolean expression for \( S \):
1. The first condition is 'motion is detected AND keycard authorization was NOT successful': This is represented as \( A \text{ AND NOT } C \) (or \( A \cdot \overline{C} \)).
2. The second condition is 'door is open AND keycard authorization was NOT successful': This is represented as \( B \text{ AND NOT } C \) (or \( B \cdot \overline{C} \)).
3. These two conditions are combined with an OR operator, representing that either situation will trigger the alarm.

Therefore, the overall unsimplified Boolean expression is:
\( S = (A \text{ AND NOT } C) \text{ OR } (B \text{ AND NOT } C) \) or algebraically \( S = A\overline{C} + B\overline{C} \).

評分準則

Award marks as follows:
- 1 mark for \( A \text{ AND NOT } C \) (or equivalent algebraic representation: \( A\overline{C} \) or \( A \cdot \text{NOT } C \)).
- 1 mark for \( B \text{ AND NOT } C \) (or equivalent algebraic representation: \( B\overline{C} \) or \( B \cdot \text{NOT } C \)).
- 0.5 marks for combining the two terms with an OR operator (addition symbol \( + \)).

Accept alternative notations such as:
- \( S = A \cdot \overline{C} + B \cdot \overline{C} \)
- \( S = (A \land \neg C) \lor (B \land \neg C) \)
- \( S = (A \text{ AND } \overline{C}) \text{ OR } (B \text{ AND } \overline{C}) \)
題目 28 · Logic Circuit Design
2.5
A logic circuit consists of three inputs \( X \), \( Y \), and \( Z \), and an output \( Q \).
- Inputs \( X \) and \( Y \) are connected to the input of a NOR gate.
- The output of this NOR gate and the input \( Z \) are connected to the input of an AND gate.
- The output of this AND gate is connected to the input of a NOT gate to produce the final output \( Q \).

Write the unsimplified Boolean expression for the output \( Q \) in terms of \( X \), \( Y \), and \( Z \).
查看答案詳解

解題

Let's trace the logic circuit from inputs to output:
1. The NOR gate with inputs \( X \) and \( Y \) produces: \( \text{NOT}(X \text{ OR } Y) \) or algebraically \( \overline{X + Y} \).
2. The AND gate has two inputs: the output of the NOR gate, and \( Z \). Its output is: \( \text{NOT}(X \text{ OR } Y) \text{ AND } Z \) or algebraically \( \overline{X + Y} \cdot Z \).
3. The NOT gate inverts the output of the AND gate to yield \( Q \): \( Q = \text{NOT}(\text{NOT}(X \text{ OR } Y) \text{ AND } Z) \) or algebraically \( Q = \overline{\overline{X + Y} \cdot Z} \).

評分準則

Award marks as follows:
- 1 mark for the correct NOR term: \( \overline{X + Y} \) or \( \text{NOT}(X \text{ OR } Y) \).
- 1 mark for the AND term combining the NOR output and \( Z \): \( \overline{X + Y} \cdot Z \) or \( \text{NOT}(X \text{ OR } Y) \text{ AND } Z \).
- 0.5 marks for the outer NOT gate inversion over the whole expression: \( \overline{\overline{X + Y} \cdot Z} \) or \( \text{NOT}(\text{NOT}(X \text{ OR } Y) \text{ AND } Z) \).

Accept equivalent alternative notation structures, such as Boolean algebra symbols.
題目 29 · Bitwise & Assembly Analysis
1
The Accumulator (ACC) currently holds the 8-bit binary value \(11010110\). The assembly language instruction \(\text{AND } \#\&0\text{F}\) is executed. State the 8-bit binary value that will be in the Accumulator after the execution of this instruction.
查看答案詳解

解題

1. Convert the immediate hexadecimal operand \(\&0\text{F}\) to its 8-bit binary representation: \(00001111\).
2. Perform a bitwise AND operation between the initial Accumulator value and the operand:
- \(1 \text{ AND } 0 = 0\)
- \(1 \text{ AND } 0 = 0\)
- \(0 \text{ AND } 0 = 0\)
- \(1 \text{ AND } 0 = 0\)
- \(0 \text{ AND } 1 = 0\)
- \(1 \text{ AND } 1 = 1\)
- \(1 \text{ AND } 1 = 1\)
- \(0 \text{ AND } 1 = 0\)
3. Combining these bits gives the final result: \(00000110\).

評分準則

1 mark for the correct 8-bit binary string: 00000110.
題目 30 · Bitwise & Assembly Analysis
1
The Accumulator (ACC) currently holds the 8-bit binary value \(10110100\). The assembly language instruction \(\text{LSR } 2\) is executed. State the 8-bit binary value in the Accumulator after the execution of this instruction.
查看答案詳解

解題

1. Identify the shift operation: \(\text{LSR } 2\) represents a Logical Shift Right by 2 positions.
2. In a logical shift right, bits shifted out on the right are discarded, and 0s are shifted into the vacated positions on the left.
3. First shift: \(10110100 \rightarrow 01011010\).
4. Second shift: \(01011010 \rightarrow 00101101\).

評分準則

1 mark for the correct 8-bit binary string: 00101101.
題目 31 · Bitwise & Assembly Analysis
1
The Accumulator (ACC) currently holds the 8-bit binary value \(01010101\). The assembly language instruction \(\text{OR } \#\&\text{F}0\) is executed. State the 8-bit binary value in the Accumulator after the execution of this instruction.
查看答案詳解

解題

1. Convert the hexadecimal operand \(\&\text{F}0\) to its 8-bit binary representation: \(11110000\).
2. Perform a bitwise OR operation between the initial Accumulator value and the operand:
- \(0 \text{ OR } 1 = 1\)
- \(1 \text{ OR } 1 = 1\)
- \(0 \text{ OR } 1 = 1\)
- \(1 \text{ OR } 1 = 1\)
- \(0 \text{ OR } 0 = 0\)
- \(1 \text{ OR } 0 = 1\)
- \(0 \text{ OR } 0 = 0\)
- \(1 \text{ OR } 0 = 1\)
3. Combining these bits gives the final result: \(11110101\).

評分準則

1 mark for the correct 8-bit binary string: 11110101.
題目 32 · Bitwise & Assembly Analysis
1
The Accumulator (ACC) currently holds the 8-bit binary value \(10101010\). The assembly language instruction \(\text{XOR } \#\&\text{AA}\) is executed. State the 8-bit binary value in the Accumulator after the execution of this instruction.
查看答案詳解

解題

1. Convert the hexadecimal operand \(\&\text{AA}\) to its 8-bit binary representation: \(10101010\).
2. Perform a bitwise XOR operation between the initial Accumulator value and the operand.
3. Since both binary values are identical (\(10101010 \text{ XOR } 10101010\)), every bit position contains identical values, resulting in \(0\) for each bit:
- \(1 \text{ XOR } 1 = 0\)
- \(0 \text{ XOR } 0 = 0\)
- ...
4. Thus, the final value is \(00000000\).

評分準則

1 mark for the correct 8-bit binary string: 00000000.

Paper 21 - Problem-solving and Programming Skills

Answer all questions. You must use the pseudocode guide enclosed in the insert to design your programmatic solutions.
16 題目 · 75
題目 1 · Pseudocode Subroutine Design
6.4
An email address is provided as a string parameter. Write a pseudocode function `ExtractDomain` that takes a single string parameter `Email` and returns the domain part of the email address (i.e., all characters after the '@' character).

The design must satisfy the following requirements:
- Assume that the string contains at most one '@' character.
- If the '@' character is not present in the string, or if it is the very last character of the string, the function must return an empty string ("").
- You must use standard pseudocode functions such as `LENGTH(String : STRING) RETURNS INTEGER` and `MID(String : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING`.
查看答案詳解

解題

The function extracts the domain name from an email address using string scanning operations.
1. `LENGTH(Email)` determines the total number of characters in the email string.
2. A `FOR` loop iterates from index 1 up to `Length`, extracting each character with `MID(Email, i, 1)`.
3. If an '@' character is found, its position `i` is stored in the `AtPos` variable.
4. After the loop, the algorithm checks if '@' is missing (`AtPos = 0`) or is the last character of the string (`AtPos = Length`). If either condition is true, an empty string `""` is returned.
5. If the domain is valid, `MID(Email, AtPos + 1, Length - AtPos)` extracts the characters from the index after '@' to the end of the string, and the result is returned.

評分準則

Mark breakdown (Total 6.4 marks):
- 1.0 mark: Correct FUNCTION header and ENDFUNCTION statement, specifying parameter types and return type.
- 1.0 mark: Correct declaration and initialization of tracking variables (e.g., length, loop index, '@' position tracker).
- 1.0 mark: Correctly structured loop scanning through the entire length of the string using `MID`.
- 1.0 mark: Correct check inside the loop to identify and save the position of the '@' character.
- 1.0 mark: Correct condition checking if '@' is missing or at the last index, returning an empty string `""`.
- 1.4 marks: Correct calculation of starting index and remaining length parameters in the extraction `MID()` statement, returning the correct domain substring.
題目 2 · Pseudocode Subroutine Design
6.4
A 1D array `DataList` of size 50 contains integer values sorted in ascending order. Write a pseudocode procedure `PrintDuplicates` that takes this sorted array as a parameter. The procedure must find and output each integer value that appears more than once in the array, along with its total frequency (the number of times it appears). Each duplicate value must be output only once.

For example, if the array contains:
[12, 12, 12, 15, 20, 20, 31, ...]

The output should be:
12 appears 3 times
20 appears 2 times
查看答案詳解

解題

Because the array is already sorted, duplicate numbers are adjacent to each other.
1. An outer `WHILE` loop is initialized with index `i <- 1` to process the entire array up to index 50.
2. In each iteration, the number at index `i` is stored in `CurrentValue`, and `Count` is initialized to 0.
3. An inner nested `WHILE` loop continues to increment `Count` and advance the array pointer `i` as long as `i` is within bounds (`i <= 50`) and the value at `DataList[i]` equals `CurrentValue`.
4. When a new number or the end of the array is reached, the inner loop terminates. If `Count > 1`, the value and its final count are printed.
5. Since the pointer `i` is advanced inside the inner loop, each element is visited only once, making this an efficient \(O(n)\) algorithm.

評分準則

Mark breakdown (Total 6.4 marks):
- 1.0 mark: Correct PROCEDURE header with array parameter defined with correct dimensions and base types.
- 1.0 mark: Correct declaration of loop variables and initialization of index pointer `i` to 1.
- 1.0 mark: Correctly structured outer loop running while index is less than or equal to 50.
- 1.0 mark: Correct inner loop structure that compares adjacent items and increments `Count`.
- 1.0 mark: Correctly handles bounds safety (`i <= 50`) in the inner loop condition to prevent index out of bounds errors.
- 1.4 marks: Correctly evaluates `Count > 1` post-inner loop and outputs the exact requested text pattern.
題目 3 · Pseudocode Subroutine Design
6.4
Write a pseudocode function `ValidatePassword` that takes a string parameter `Password` and returns a boolean value (`TRUE` if the password is valid, `FALSE` otherwise).

A password is valid if and only if it meets all of the following rules:
1. It must contain at least 8 characters.
2. It must contain at least one uppercase alphabetical character ('A' to 'Z').
3. It must contain at least one lowercase alphabetical character ('a' to 'z').

You must use standard pseudocode and functions such as `LENGTH` and `MID`.
查看答案詳解

解題

This routine parses a password string to enforce common validation constraints.
1. First, the function checks the minimum length of the password using `LENGTH(Password)`. If it is less than 8, it short-circuits and immediately returns `FALSE`.
2. Two boolean flags `HasUpper` and `HasLower` are declared and initialized to `FALSE`.
3. A `FOR` loop evaluates each character of the password string from index 1 to `Length` using `MID(Password, i, 1)`.
4. If a character falls within range `"A"` to `"Z"`, `HasUpper` is flagged as `TRUE`. If it falls within range `"a"` to `"z"`, `HasLower` is flagged as `TRUE`.
5. Once the loop ends, the function returns `TRUE` only if both tracking variables are `TRUE`. Otherwise, it returns `FALSE`.

評分準則

Mark breakdown (Total 6.4 marks):
- 1.0 mark: Correct FUNCTION header specifying the parameter and a BOOLEAN return type.
- 1.0 mark: Correct length check enforcing that a password shorter than 8 returns `FALSE`.
- 1.0 mark: Correct declaration and initialization of boolean tracker flags to `FALSE`.
- 1.0 mark: Correct implementation of a loop running through each character of the string.
- 1.0 mark: Correct ASCII range comparison logic to detect both uppercase and lowercase characters.
- 1.4 marks: Correct boolean evaluation at the end of the function returning the exact validation outcome.
題目 4 · Pseudocode Subroutine Design
6.4
An inventory database uses a user-defined record type `Item` defined as follows:

```pseudocode
TYPE Item
DECLARE ID : STRING
DECLARE Price : REAL
DECLARE Quantity : INTEGER
ENDTYPE
```

An array `Inventory` is declared as:
`DECLARE Inventory : ARRAY[1:200] OF Item`

Write a pseudocode function `CalculateValue` that takes this array and a single character `Category` (of type `CHAR`) as parameters. The function must calculate and return the total monetary value (i.e., `Price * Quantity` for each item) of all items whose `ID` starts with the specified `Category` character.
查看答案詳解

解題

1. The function is declared to accept an array of 200 `Item` structures and a search character `Category`, returning a cumulative sum of type `REAL`.
2. A running total `Total` is declared and initialized to `0.0`.
3. A loop cycles through indices 1 to 200 of the `Inventory` array.
4. Within each iteration, the ID is inspected. To prevent runtime indexing errors, the length is validated.
5. The starting character of the item's ID is retrieved using `MID(ItemID, 1, 1)` and compared to `Category`.
6. If they match, the current record's `Price` and `Quantity` are multiplied and added to `Total`.
7. Finally, `Total` is returned after completing the array traversal.

評分準則

Mark breakdown (Total 6.4 marks):
- 1.0 mark: Correct FUNCTION header and ENDFUNCTION statement, accepting the defined record array and returning a `REAL` variable.
- 1.0 mark: Initializing the floating-point total tracker `Total` to `0.0`.
- 1.0 mark: Correct loop bounds iterating through all 200 array records.
- 1.0 mark: Correct syntax for accessing fields of a record stored in an array element (e.g. `Inventory[i].Price`).
- 1.0 mark: Correct check to isolate the first letter of `ID` using string slicing functions.
- 1.4 marks: Correct calculation and update of total value, and returning the correct final total after loop completion.
題目 5 · Pseudocode Subroutine Design
6.4
A text file `LogFile.txt` stores logs of user login attempts. Each line contains a username, date, and status separated by commas, formatted as: `Username,Date,Status` (for example, "alice,2023-11-05,SUCCESS" or "bob,2023-11-05,FAILED").

A pre-existing helper function is available:
`ExtractField(Line : STRING, FieldNum : INTEGER) RETURNS STRING`
- `FieldNum = 1` returns the Username.
- `FieldNum = 2` returns the Date.
- `FieldNum = 3` returns the Status.

Write a pseudocode function `CountFailedLogins` that takes a string `TargetUser` as a parameter. The function must:
1. Open the file `LogFile.txt` for reading.
2. Read through all lines in the file.
3. Use the helper function `ExtractField` to extract the username and status of each attempt.
4. Count how many times the `TargetUser` has a status equal to "FAILED".
5. Close the file.
6. Return the accumulated count as an integer.
查看答案詳解

解題

The algorithm implements file streaming and parsing concepts:
1. The function is defined to take a `TargetUser` parameter and return an integer.
2. We open `LogFile.txt` using `OPENFILE "LogFile.txt" FOR READ`.
3. A standard sentinel-controlled loop is used: `WHILE NOT EOF("LogFile.txt")` ensures we read lines until the end of the file is reached.
4. In each step, we use `READFILE` to load the current line into the local string variable `Line`.
5. We extract the relevant properties of the login record by calling the helper function `ExtractField(Line, 1)` for the username and `ExtractField(Line, 3)` for the status.
6. We compare the extracted username to the `TargetUser` and the status to `"FAILED"`. If both are equal, we increment our counter.
7. Finally, we close the text file with `CLOSEFILE "LogFile.txt"` and return the total count.

評分準則

Mark breakdown (Total 6.4 marks):
- 1.0 mark: Correct FUNCTION header specifying the `TargetUser` parameter and `INTEGER` return type.
- 1.0 mark: Correctly opens the file `LogFile.txt` in `READ` mode and closes it prior to returning.
- 1.0 mark: Correct loop design using `WHILE NOT EOF()` checking the correct file handle.
- 1.0 mark: Correct execution of `READFILE` to obtain the text lines consecutively.
- 1.0 mark: Correct invocation of `ExtractField` with correct parameters for fields 1 and 3.
- 1.4 marks: Correct conditional block verifying both the Username and "FAILED" status, incrementing the counter, and returning the correct value.
題目 6 · Tracing & Symbolic Representation
5
An algorithm is represented by the following pseudocode function:

```
FUNCTION ProcessString(InputStr : STRING) RETURNS STRING
DECLARE Length : INTEGER
DECLARE ResultStr : STRING
DECLARE i : INTEGER
DECLARE Ch : CHAR

Length <- LENGTH(InputStr)
ResultStr <- ""

FOR i <- 1 TO Length
Ch <- MID(InputStr, i, 1)
IF i MOD 2 = 1 THEN
IF Ch >= 'a' AND Ch <= 'z' THEN
ResultStr <- ResultStr + TO_UPPER(Ch)
ELSE
ResultStr <- ResultStr + Ch
ENDIF
ELSE
IF Ch >= 'A' AND Ch <= 'Z' THEN
ResultStr <- ResultStr + TO_LOWER(Ch)
ELSE
ResultStr <- ResultStr + "*"
ENDIF
ENDIF
NEXT i
RETURN ResultStr
ENDFUNCTION
```

Complete the trace table below for the function call: `ProcessString("c6H!p")`.

| Length | i | Ch | ResultStr |
|---|---|---|---|
| | | | |

*Note: You may not need to use all rows of the table. State your final returned value clearly.*
查看答案詳解

解題

Step-by-step evaluation of the code:
1. `Length` is set to the length of the string "c6H!p", which is 5.
2. `ResultStr` is initialized to "".
3. The loop runs for `i` from 1 to 5:
- `i = 1` (odd): `Ch` is 'c'. Since 'c' is a lowercase letter, it is converted to uppercase 'C'. `ResultStr` becomes "C".
- `i = 2` (even): `Ch` is '6'. Since it is not an uppercase letter, the code falls to the ELSE statement and appends '*'. `ResultStr` becomes "C*".
- `i = 3` (odd): `Ch` is 'H'. Since 'H' is not a lowercase letter, the code falls to the ELSE statement and appends 'H' unchanged. `ResultStr` becomes "C*H".
- `i = 4` (even): `Ch` is '!'. Since it is not an uppercase letter, it appends '*'. `ResultStr` becomes "C*H*".
- `i = 5` (odd): `Ch` is 'p'. Since 'p' is a lowercase letter, it is converted to uppercase 'P'. `ResultStr` becomes "C*H*P".
4. The loop terminates and the function returns "C*H*P".

評分準則

1 mark: Correct evaluation of Length (5) and initialization of ResultStr to "".
1 mark: Correct tracking of loop index `i` (1 to 5) and extraction of corresponding characters for `Ch`.
1 mark: Correct string manipulation on odd positions (converting 'c' to 'C', keeping 'H' as 'H', converting 'p' to 'P').
1 mark: Correct string manipulation on even positions (converting '6' to '*', converting '!' to '*').
1 mark: Correct final returned value of "C*H*P" following correct intermediate steps.
題目 7 · Tracing & Symbolic Representation
5
An array `Arr` contains the following elements:
`[4, 7, 3, 3, 8, 2]`

An algorithm is written to process this array as follows:

```
FUNCTION ComputeHash(Arr : ARRAY[1..6] OF INTEGER) RETURNS INTEGER
DECLARE i : INTEGER
DECLARE Temp : INTEGER
DECLARE HashVal : INTEGER

HashVal <- 0
Temp <- Arr[1]

FOR i <- 2 TO 6
IF Arr[i] > Temp THEN
HashVal <- HashVal + (Arr[i] - Temp) * i
Temp <- Arr[i]
ELSE
HashVal <- HashVal - (Temp - Arr[i])
Temp <- Temp - 1
ENDIF
NEXT i

RETURN HashVal
ENDFUNCTION
```

Complete the trace table below for the function call: `ComputeHash(Arr)`.

| i | Arr[i] | Temp | HashVal |
|---|---|---|---|
| | | | |

*Note: Start by documenting the initial states of variables prior to the loop.*
查看答案詳解

解題

Tracing steps:
- **Initial values**: `HashVal` starts at 0, and `Temp` is assigned `Arr[1]`, which is 4.
- **i = 2**: `Arr[2]` is 7. Since \(7 > 4\) is True:
- `HashVal` = \(0 + (7 - 4) \times 2 = 6\)
- `Temp` = \(Arr[2] = 7\)
- **i = 3**: `Arr[3]` is 3. Since \(3 > 7\) is False:
- `HashVal` = \(6 - (7 - 3) = 2\)
- `Temp` = \(7 - 1 = 6\)
- **i = 4**: `Arr[4]` is 3. Since \(3 > 6\) is False:
- `HashVal` = \(2 - (6 - 3) = -1\)
- `Temp` = \(6 - 1 = 5\)
- **i = 5**: `Arr[5]` is 8. Since \(8 > 5\) is True:
- `HashVal` = \(-1 + (8 - 5) \times 5 = 14\)
- `Temp` = \(Arr[5] = 8\)
- **i = 6**: `Arr[6]` is 2. Since \(2 > 8\) is False:
- `HashVal` = \(14 - (8 - 2) = 8\)
- `Temp` = \(8 - 1 = 7\)
- **Loop ends**: The final value of `HashVal` returned is 8.

評分準則

1 mark: Correct initial states documented (`Temp = 4`, `HashVal = 0`).
1 mark: Correct row state for `i = 2` (`HashVal = 6`, `Temp = 7`).
1 mark: Correct row states for `i = 3` and `i = 4` showing correct application of the ELSE branch (HashVal drops to 2 and then to -1; Temp decrements correctly to 6 and then to 5).
1 mark: Correct row state for `i = 5` (`HashVal = 14`, `Temp = 8`).
1 mark: Correct row state for `i = 6` (`HashVal = 8`, `Temp = 7`) and correct final returned value of 8.
題目 8 · Tracing & Symbolic Representation
5
The following recursive function is written in pseudocode:

```
FUNCTION Mystery(A : INTEGER, B : INTEGER) RETURNS INTEGER
IF B = 0 THEN
RETURN 0
ELSE
IF B MOD 2 = 0 THEN
RETURN Mystery(A * 2, B DIV 2)
ELSE
RETURN A + Mystery(A * 2, B DIV 2)
ENDIF
ENDIF
ENDFUNCTION
```

(a) Show the sequence of recursive calls and the return value of each call during the evaluation of `Mystery(7, 5)`. [3]

(b) State the base case condition of this function. [1]

(c) State the mathematical operation performed by `Mystery(A, B)` in terms of \(A\) and \(B\) for positive integers. [1]
查看答案詳解

解題

(a) Step-by-step trace of recursive calls:
1. `Mystery(7, 5)`: Since `B` (5) is not 0, and `5 MOD 2 = 1` (odd), it returns `7 + Mystery(7 * 2, 5 DIV 2)` -> `7 + Mystery(14, 2)`.
2. `Mystery(14, 2)`: Since `B` (2) is not 0, and `2 MOD 2 = 0` (even), it returns `Mystery(14 * 2, 2 DIV 2)` -> `Mystery(28, 1)`.
3. `Mystery(28, 1)`: Since `B` (1) is not 0, and `1 MOD 2 = 1` (odd), it returns `28 + Mystery(28 * 2, 1 DIV 2)` -> `28 + Mystery(56, 0)`.
4. `Mystery(56, 0)`: Since `B = 0`, the base case is reached. It returns `0` directly.

Now, substitute the returned values back up the call stack:
- `Mystery(28, 1)` returns `28 + 0 = 28`
- `Mystery(14, 2)` returns `28`
- `Mystery(7, 5)` returns `7 + 28 = 35`

(b) The base case is when the execution stops calling itself, which occurs when the condition `B = 0` is satisfied.

(c) The function implements binary multiplication (also known as Russian Peasant Multiplication). The expression simplifies to calculating the product of \(A\) and \(B\), i.e., \(A \times B\).

評分準則

Part (a) [3 marks]:
- 1 mark: Correct sequence of recursive calls with correct arguments: `Mystery(7, 5)` -> `Mystery(14, 2)` -> `Mystery(28, 1)` -> `Mystery(56, 0)`.
- 1 mark: Correct base case return value of 0, and correct execution of back-substitution equations (e.g. `28 + 0`).
- 1 mark: Correct final return value of 35.

Part (b) [1 mark]:
- 1 mark: Correctly identifies the base case condition as `B = 0`.

Part (c) [1 mark]:
- 1 mark: Correctly identifies that the function computes the product / multiplication of `A` and `B` (accept: \(A \times B\) or similar).
題目 9 · Structured Program Logic Explanations
3.5
Analyse the pseudocode provided below, which is designed to validate an identifier string.

```
FUNCTION IsValidID(ID : STRING) RETURNS BOOLEAN
DECLARE i : INTEGER
DECLARE Valid : BOOLEAN
DECLARE Ch : CHAR
IF LENGTH(ID) = 0 THEN
RETURN FALSE
ENDIF
Ch <- MID(ID, 1, 1)
IF NOT ((Ch >= 'a' AND Ch <= 'z') OR (Ch >= 'A' AND Ch <= 'Z')) THEN
RETURN FALSE
ENDIF
Valid <- TRUE
i <- 2
WHILE i <= LENGTH(ID) AND Valid = TRUE
Ch <- MID(ID, i, 1)
IF NOT ((Ch >= 'a' AND Ch <= 'z') OR (Ch >= 'A' AND Ch <= 'Z') OR (Ch >= '0' AND Ch <= '9')) THEN
Valid <- FALSE
ENDIF
i <- i + 1
ENDWHILE
RETURN Valid
ENDFUNCTION
```

Explain how the logic of the algorithm ensures that:
1. The identifier is not empty.
2. The first character is a letter.
3. Any subsequent characters are alphanumeric.
查看答案詳解

解題

The function performs structure-based validation stepwise:
1. **Empty String Validation**: The statement `IF LENGTH(ID) = 0 THEN RETURN FALSE` acts as a guard clause, returning false instantly if the length is zero before any characters are accessed.
2. **First Character Validation**: It isolates the character at index 1 with `MID(ID, 1, 1)` and compares it against range values for ASCII letters. If it falls outside both ranges `['a'..'z']` and `['A'..'Z']`, it exits the function with `FALSE`.
3. **Remaining Characters Validation**: A loop starting from index 2 iterates through the string. During each iteration, `MID(ID, i, 1)` retrieves the current character, checking if it is a lowercase letter, uppercase letter, or numeric digit. If any character violates this, the flag `Valid` is set to `FALSE`, which immediately causes the loop to terminate on the next check `AND Valid = TRUE` and eventually returns `FALSE`.

評分準則

Max 3.5 marks:
- **1 Mark**: Explaining that `LENGTH(ID) = 0` checks if the string is empty and immediately halts execution by returning `FALSE`.
- **1 Mark**: Explaining how the first character is isolated using `MID(ID, 1, 1)` and evaluated against alphabetic ranges, returning `FALSE` if invalid.
- **1.5 Marks**: Explaining the loop index initialization (`i <- 2`), the compound termination condition (`i <= LENGTH(ID) AND Valid = TRUE`), and the use of ranges to flag invalid alphanumeric characters.
題目 10 · Structured Program Logic Explanations
3.5
A developer is writing a procedure to search for an item in an array using a conditional loop. Explain how the interaction between the boolean flag `FOUND` and the index variable `INDEX` in the logic below optimizes the search compared to a standard count-controlled loop (`FOR` loop) that runs through the entire array.

```
FOUND <- FALSE
INDEX <- 1
WHILE INDEX <= MaxItems AND NOT FOUND
IF ItemList[INDEX] = SearchTarget THEN
FOUND <- TRUE
ELSE
INDEX <- INDEX + 1
ENDIF
ENDWHILE
```
查看答案詳解

解題

In a count-controlled `FOR` loop, the loop runs for a fixed number of times regardless of when the item is found, wasting computational resources. In this conditional loop:
- The loop condition uses a compound boolean expression: `INDEX <= MaxItems AND NOT FOUND`.
- As long as `FOUND` is `FALSE` and the end of the array has not been reached, the loop continues.
- Once `ItemList[INDEX] = SearchTarget` becomes `TRUE`, `FOUND` is set to `TRUE`.
- In the next iteration check, `NOT FOUND` evaluates to `FALSE`, causing the entire condition to evaluate to `FALSE`.
- This immediately terminates the loop without incrementing `INDEX` or evaluating any further array elements, optimizing average-case performance.

評分準則

Max 3.5 marks:
- **1 Mark**: Identifying that the compound loop condition includes `NOT FOUND` which terminates the loop immediately when the element is found.
- **1 Mark**: Explaining that a standard `FOR` loop is count-controlled and must execute until its upper limit is reached regardless of whether the target is found.
- **1.5 Marks**: Describing how this avoids redundant iterations, saving processor time and optimizing execution in the average case where the item is located early in the array.
題目 11 · Structured Program Logic Explanations
3.5
Explain the logical purpose of the boolean variable `Swapped` and the statement `n <- n - 1` in the provided bubble sort implementation, detailing how they improve the efficiency of the sorting process.

```
DECLARE Swapped : BOOLEAN
DECLARE Temp, i, n : INTEGER
n <- 10
REPEAT
Swapped <- FALSE
FOR i <- 1 TO n - 1
IF Arr[i] > Arr[i+1] THEN
Temp <- Arr[i]
Arr[i] <- Arr[i+1]
Arr[i+1] <- Temp
Swapped <- TRUE
ENDIF
ENDFOR
n <- n - 1
UNTIL NOT Swapped
```
查看答案詳解

解題

The logical components optimize bubble sort in two distinct ways:
1. **Early Termination via `Swapped`**: Before each pass, `Swapped` is set to `FALSE`. If any adjacent elements are out of order, they are swapped and `Swapped` is updated to `TRUE`. If a complete pass finishes and `Swapped` is still `FALSE`, it means no adjacent elements were out of order, indicating the array is completely sorted. The outer `REPEAT...UNTIL NOT Swapped` loop detects this and terminates, preventing redundant passes.
2. **Reducing Comparison Boundary via `n <- n - 1`**: With each complete pass of bubble sort, the largest value in the unsorted portion of the array 'bubbles up' to its final correct position at the end. Therefore, it is no longer necessary to compare elements in the sorted tail. Decrementing `n` by 1 after each pass shrinks the limit of the inner `FOR` loop, avoiding useless comparisons on elements already sorted.

評分準則

Max 3.5 marks:
- **1.5 Marks**: Detail on `Swapped` - tracking if any adjacent swap occurred during a pass, and halting the outer loop early (`UNTIL NOT Swapped`) when the array is already sorted.
- **2 Marks**: Detail on `n <- n - 1` - recognizing that the largest unsorted element settles into its correct position at the end of each pass, thus decreasing `n` reduces the bounds of the inner loop to skip already sorted elements, saving CPU cycles.
題目 12 · Structured Program Logic Explanations
3.5
Study the pseudocode routine below designed to read data from an external sequential file and calculate an average. Explain the structural logic used to handle (i) a completely empty file, and (ii) the loop terminating correctly when the end of the file is reached.

```
DECLARE Total, Count : INTEGER
DECLARE Value : INTEGER
Total <- 0
Count <- 0
OPENFILE "Scores.txt" FOR READ
IF NOT EOF("Scores.txt") THEN
WHILE NOT EOF("Scores.txt")
READFILE "Scores.txt", Value
Total <- Total + Value
Count <- Count + 1
ENDWHILE
OUTPUT "Average: ", Total / Count
ELSE
OUTPUT "File is empty"
ENDIF
CLOSEFILE "Scores.txt"
```
查看答案詳解

解題

The algorithm prevents runtime errors through two primary structural guards:
1. **Empty File Handling**: The outer `IF NOT EOF("Scores.txt")` statement verifies whether the file contains any records before attempting to perform operations. If the file is empty, the program executes the `ELSE` block, outputs "File is empty", and bypasses the average calculation. This prevents a division-by-zero runtime error because `Count` would remain 0.
2. **Loop Termination**: The `WHILE NOT EOF("Scores.txt")` loop iteratively tests whether there is remaining data. Inside the loop, `READFILE` advances the file pointer. As soon as the last record is read, the end-of-file condition `EOF("Scores.txt")` becomes `TRUE`, which makes the loop condition `NOT EOF` evaluate to `FALSE`. The loop terminates cleanly without attempts to read past the end of the file.

評分準則

Max 3.5 marks:
- **1.5 Marks**: Explaining how the initial `IF NOT EOF` check branches the program away from logic that would result in division-by-zero (`Total / Count` when `Count` is 0) if the file contains no data.
- **2 Marks**: Explaining how the `WHILE NOT EOF` loop dynamically checks the file status, and how reading lines sequentially advances the file pointer until EOF becomes true, resulting in clean termination.
題目 13 · Structured Program Logic Explanations
3.5
The recursive function `Power` is defined below. Explain how the base case prevents infinite recursion and outline the step-by-step logic of how the system processes the call `Power(3, 3)` using the stack.

```
FUNCTION Power(Base : INTEGER, Exp : INTEGER) RETURNS INTEGER
IF Exp = 0 THEN
RETURN 1
ELSE
RETURN Base * Power(Base, Exp - 1)
ENDIF
ENDFUNCTION
```
查看答案詳解

解題

1. **Base Case Prevention of Infinite Recursion**: The base case is `Exp = 0`. With each recursive call, the parameter `Exp` is decremented by 1 (`Exp - 1`). Because the decrement moves `Exp` closer to 0, it is guaranteed to eventually equal 0. When `Exp = 0`, the function returns 1 directly without making any further calls, halting the recursive chain.
2. **Stack Processing of `Power(3, 3)`**:
- **Phase 1: Winding (Pushing onto Stack)**:
- `Power(3, 3)` calls `3 * Power(3, 2)`. This call is suspended, state is pushed.
- `Power(3, 2)` calls `3 * Power(3, 1)`. Suspended, state is pushed.
- `Power(3, 1)` calls `3 * Power(3, 0)`. Suspended, state is pushed.
- `Power(3, 0)` triggers the base case and returns `1` immediately.
- **Phase 2: Unwinding (Popping from Stack)**:
- `Power(3, 1)` resumes: `3 * 1 = 3`. Returns `3`.
- `Power(3, 2)` resumes: `3 * 3 = 9`. Returns `9`.
- `Power(3, 3)` resumes: `3 * 9 = 27`. Returns the final value `27`.

評分準則

Max 3.5 marks:
- **1 Mark**: Explaining that the base case `Exp = 0` stops recursive calls, returning a constant value of 1, and that `Exp - 1` ensures progress toward the base case.
- **1.5 Marks**: Detailed trace of execution showing the generation of recursive calls: `Power(3,3)`, `Power(3,2)`, `Power(3,1)`, and `Power(3,0)`.
- **1 Mark**: Describing stack unwinding where deferred multiplications are resolved in reverse order to compute the final result of 27.
題目 14 · Structured Program Logic Explanations
3.5
The pseudocode below processes a 2D array named `Grid` of dimensions `[1:10, 1:5]`. Explain the structural logic of the nested loops, detailing why the outer loop controls the column index and the inner loop controls the row index to achieve the intended output.

```
DECLARE Row, Col, ColTotal : INTEGER
FOR Col <- 1 TO 5
ColTotal <- 0
FOR Row <- 1 TO 10
ColTotal <- ColTotal + Grid[Row, Col]
ENDFOR
OUTPUT "Column Total: ", ColTotal
ENDFOR
```
查看答案詳解

解題

This nested loop structural logic is designed for column-by-column processing:
1. **Outer Loop Control (`Col` loop)**: The outer loop iterates through column indexes 1 to 5. For each column, it initializes `ColTotal` to 0, ensuring that the summation starts fresh for each column.
2. **Inner Loop Control (`Row` loop)**: For a single, fixed value of `Col` (e.g., column 1), the inner loop runs 10 times, incrementing `Row` from 1 to 10. This accesses `Grid[Row, Col]`, which travels down the rows of that specific column, accumulating their values into `ColTotal`.
3. **Result Output**: After the inner loop completes its 10 iterations (meaning one column is finished), the output statement displays that column's total. Only then does the outer loop step to the next column index, repeating the process for all columns.

評分準則

Max 3.5 marks:
- **1 Mark**: Identifying that the outer loop fixes the column index and resets `ColTotal` to 0 for each new column iteration.
- **1.5 Marks**: Explaining that the inner loop iterates through all row indices (1 to 10) for the current fixed column, meaning values are accumulated down a vertical column rather than across rows.
- **1 Mark**: Explaining that the placement of the `OUTPUT` statement outside the inner loop but inside the outer loop guarantees that the calculated total is printed exactly once per column.
題目 15 · Structured Program Logic Explanations
3.5
Consider the procedure `Adjust` defined below. Suppose the main program runs the following statements:
```
Num1 <- 20
Num2 <- 30
Adjust(Num1, Num2)
```
Explain the logic behind the final values of `Num1` and `Num2` in the main program after the procedure call, highlighting the difference in parameter passing methods.

```
PROCEDURE Adjust(BYREF X : INTEGER, BYVAL Y : INTEGER)
X <- X + 10
Y <- Y + 5
ENDPROCEDURE
```
查看答案詳解

解題

The parameter passing methods determine how changes propagate back:
1. **BYREF (By Reference)**: Parameter `X` is mapped to `Num1`. By passing by reference, a pointer pointing directly to the memory address of `Num1` is sent. When `X <- X + 10` is executed, the statement modifies the actual memory location of `Num1`. Therefore, `Num1` changes from 20 to 30, and this change persists after the procedure finishes.
2. **BYVAL (By Value)**: Parameter `Y` is mapped to `Num2`. By passing by value, a duplicate copy of the value (30) is created and stored in a new local variable `Y`. Inside the procedure, `Y <- Y + 5` increases `Y` to 35, but this only affects the temporary copy. The original variable `Num2` remains unchanged, retaining its original value of 30.

評分準則

Max 3.5 marks:
- **1.5 Marks**: Clear explanation of `BYREF` (for `Num1` / `X`) - passing the memory location, resulting in changes within the procedure modifying the original variable directly (final value 30).
- **2 Marks**: Clear explanation of `BYVAL` (for `Num2` / `Y`) - passing a duplicate local copy of the value, which isolates the original variable from modification inside the procedure (final value 30).
題目 16 · Structured Program Logic Explanations
3.5
Explain how the logic of the `ExtractMonth` function below extracts the month from the date string, and how it handles validation of both structural integrity and the logical range of the month.

```
FUNCTION ExtractMonth(DateStr : STRING) RETURNS INTEGER
DECLARE MonthStr : STRING
DECLARE MonthNum : INTEGER
IF LENGTH(DateStr) <> 10 THEN
RETURN -1
ENDIF
MonthStr <- MID(DateStr, 4, 2)
MonthNum <- STRING_TO_NUM(MonthStr)
IF MonthNum < 1 OR MonthNum > 12 THEN
RETURN -1
ENDIF
RETURN MonthNum
ENDFUNCTION
```
查看答案詳解

解題

The logical steps of the validation and parsing routine are:
1. **Structural Length Check**: `IF LENGTH(DateStr) <> 10` ensures that the incoming string matches the standard length of a date format (such as 'DD/MM/YYYY'). If not, it safely exits immediately by returning `-1` to prevent string index/out-of-bounds exceptions.
2. **Sub-string Extraction & Parsing**: `MID(DateStr, 4, 2)` targets the characters at indices 4 and 5 (which represent the two-digit month). It then uses `STRING_TO_NUM` to parse this extracted substring into an integer value, `MonthNum`.
3. **Logical Range Check**: The compound conditional statement `IF MonthNum < 1 OR MonthNum > 12` verifies that the numeric representation fits inside the acceptable calendar months range (1 to 12). If the month is out of range, the function returns `-1` to signal a validation error; otherwise, it returns the valid integer month.

評分準則

Max 3.5 marks:
- **1 Mark**: Explaining the structural check (`LENGTH(DateStr) <> 10`) which ensures the date string format is valid in length, returning `-1` for invalid lengths.
- **1 Mark**: Explaining that `MID(DateStr, 4, 2)` correctly targets the characters representing the month and converts them to an integer using built-in string conversion functions.
- **1.5 Marks**: Explaining the logical validation step (`MonthNum < 1 OR MonthNum > 12`) that screens out mathematically valid but calendar-invalid numbers (e.g., '00' or '13'), and how it behaves when returning the result or error flag.

想知道自己有幾分把握?

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

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

免費開始練習