Question Simulator

AS & A Level Computer Science (9618)

Further programming Banker

16 questions · about 5% of the marks we indexed · examined in 9 of 9 sessions.

Questions by year

2026

  • 2026 May/June · Paper 32 · Q10 (b)6 marksFile processing & exception handling
  • 2026 May/June · Paper 32 · Q11 (a, b)9 marksObject-oriented programming

2025

  • 2025 Oct/Nov · Paper 32 · Q10 (a, b)4 marksFile processing & exception handling
  • 2025 Oct/Nov · Paper 32 · Q117 marksProgramming paradigms & low-level programming
  • 2025 May/June · Paper 32 · Q12 (a, b(i), b(ii))8 marksObject-oriented programming
  • 2025 May/June · Paper 32 · Q135 marksFile processing & exception handling

2024

  • 2024 Oct/Nov · Paper 32 · Q10 (a, b)6 marksObject-oriented programming
  • 2024 May/June · Paper 32 · Q10 (a, b, c)9 marksDeclarative programming (Prolog)

2023

  • 2023 Oct/Nov · Paper 32 · Q11 (a, b, c)9 marksDeclarative programming (Prolog)
  • 2023 Oct/Nov · Paper 32 · Q12 (a, b)9 marksFile processing & exception handling
  • 2023 May/June · Paper 32 · Q44 marksObject-oriented programming
  • 2023 May/June · Paper 32 · Q6 (b)5 marksFile processing & exception handling

2022

  • 2022 Oct/Nov · Paper 32 · Q10 (a, b)6 marksObject-oriented programming
  • 2022 May/June · Paper 32 · Q1 (c(i), c(ii))3 marksObject-oriented programming
  • 2022 May/June · Paper 32 · Q2 (a, b, c)7 marksDeclarative programming (Prolog)
  • 2022 May/June · Paper 32 · Q94 marksFile processing & exception handling

References only, not question text. Open Official paper ↗ where Cambridge publishes the paper, or see the official Cambridge past-papers page; for other papers, ask your school. “Paper 42” means Paper 4, variant 2.

Practice questions

Original questions written by HomiLabs in the style of the exam, with answers and mark schemes. They are not Cambridge past paper questions and have not been reviewed by Cambridge. Try each one before opening the answer.

Q1Object-oriented programming · Core · Paper 3 style · 6 marks
  1. (a) Define each of these object-oriented terms.(i) class (ii) object (iii) attribute (iv) method [4]
  2. (b) Explain what is meant by encapsulation. [2]
Show answer
  1. (a) (i) A template/blueprint that defines the attributes and methods shared by objects of one type. (ii) An instance of a class, with its own values for the attributes. (iii) A data item (property) belonging to a class/object. (iv) A procedure or function defined in a class that acts on an object's data.
    1 mark each.
  2. (b) Combining the data (attributes) and the methods that act on it in one class, and hiding the data (PRIVATE) so it can only be accessed or changed through the class's own public methods.
    1 mark: data and methods bundled together in a class/object. 1 mark: attributes hidden – accessed only via methods (getters/setters).
Q2Object-oriented programming · Core · Paper 3 style · 4 marks
  1. (a) A transport app has a class Vehicle with attributes RegNumber and MaxPassengers and a method Describe(). The classes Rickshaw and Bus are derived from Vehicle. Explain what is meant by inheritance, using these classes. [2]
  2. (b) Explain what is meant by polymorphism, using the method Describe(). [2]
Show answer
  1. (a) Inheritance means a subclass (derived class) automatically gets the attributes and methods of its parent (base) class. Rickshaw and Bus inherit RegNumber, MaxPassengers and Describe() from Vehicle and can add their own, e.g. Bus could add RouteNumber.
    1 mark: subclass receives attributes and methods of the superclass. 1 mark: applied to Vehicle/Rickshaw/Bus.
  2. (b) Polymorphism allows a method inherited from the base class to be redefined (overridden) in a subclass so that it behaves differently: calling Describe() on a Rickshaw object gives a different output from calling it on a Bus object, even though both use the same method name.
    1 mark: same method name, different behaviour in different classes (overriding). 1 mark: example with Describe() for Rickshaw/Bus.
Q3Object-oriented programming · Core · Paper 3 style · 4 marks
  1. (a) In a class Student, the attribute DateOfBirth is declared PRIVATE and is accessed with the methods GetDateOfBirth() and SetDateOfBirth(). Explain why the attribute is private and accessed through these methods. [3]
  2. (b) State the purpose of a constructor. [1]
Show answer
  1. (a) Making it PRIVATE means code outside the class cannot read or change it directly (encapsulation/data hiding). Access is only through the getter and setter, so the class controls how the data is used. The setter can validate the new value (e.g. reject a future date) before storing it, keeping the object's data valid.
    1 mark each for any three of: cannot be accessed directly from outside the class; encapsulation/information hiding; getter returns the value; setter changes it in a controlled way; setter can validate data; internal representation can change without affecting other code.
  2. (b) A method that is called automatically when an object is created (instantiated), to set the initial values of its attributes.
    B1.
Q4Object-oriented programming · Standard · Paper 3 style · 8 marks
  1. (a) A bookshop in Lahore uses a class Book with these private attributes: ISBN (STRING), Title (STRING), Price (REAL). It has a constructor that takes values for all three attributes, a getter for Price and a method ApplyDiscount(Percent : INTEGER) that reduces Price by that percentage.Write pseudocode for the class Book. [6]
  2. (b) Write a pseudocode statement to create a Book object called NewBook with ISBN "978-1-7290-4471-0", title "Mountain Roads" and price 1450. [1]
  3. (c) NewBook.ApplyDiscount(20) is called. State the value then returned by NewBook.GetPrice(). [1]
Show answer
  1. (a) CLASS Book PRIVATE ISBN : STRING PRIVATE Title : STRING PRIVATE Price : REAL PUBLIC PROCEDURE NEW(GivenISBN : STRING, GivenTitle : STRING, GivenPrice : REAL) ISBN ← GivenISBN Title ← GivenTitle Price ← GivenPrice ENDPROCEDURE PUBLIC FUNCTION GetPrice() RETURNS REAL RETURN Price ENDFUNCTION PUBLIC PROCEDURE ApplyDiscount(Percent : INTEGER) Price ← Price * (100 - Percent) / 100 ENDPROCEDUREENDCLASS
    1 mark each for: CLASS Book … ENDCLASS; three PRIVATE attribute declarations with types; constructor PUBLIC PROCEDURE NEW with three parameters; assignments to the attributes in the constructor; GetPrice function returning Price; ApplyDiscount procedure with correct calculation.
  2. (b) NewBook ← NEW Book("978-1-7290-4471-0", "Mountain Roads", 1450)
    B1.
  3. (c) 1160
    B1 1450 × 80 ÷ 100 = 1160.
Q5Object-oriented programming · Standard · Paper 3 style · 6 marks
  1. (a) Explain the difference between inheritance and containment (aggregation) in object-oriented programming. Give an example of each from a school system with classes Person, Teacher and Department. [4]
  2. (b) Explain what is meant by method overriding. [2]
Show answer
  1. (a) Inheritance is an 'is a' relationship: a subclass gets the attributes and methods of a superclass – e.g. Teacher inherits from Person (a teacher is a person). Containment/aggregation is a 'has a' relationship: one class contains objects of another class as attributes – e.g. a Department has (contains) several Teacher objects.
    1 mark: inheritance = 'is a'/subclass gets parent's members. 1 mark: suitable inheritance example. 1 mark: aggregation = 'has a'/object contains other objects. 1 mark: suitable aggregation example.
  2. (b) A subclass defines its own version of a method that it has inherited, with the same name/identifier (and parameters); when the method is called on a subclass object, the subclass's version is used instead of the parent's.
    1 mark: subclass redefines an inherited method with the same name. 1 mark: subclass version runs for subclass objects.
Q6Object-oriented programming · Standard · Paper 4 style · 10 marks
  1. (a) A clinic records patients' temperatures. Write program code for a class Patient with:• private attributes PatientID (string), Name (string) and Temperature (real)• a constructor that takes all three values as parameters• a getter for each attribute• a method SetTemperature(NewTemp) that changes Temperature only if NewTemp is between 30.0 and 45.0 inclusive, returning True if the change was made and False otherwise. (Python shown; Java or VB.NET solutions are equally acceptable.) [7]
  2. (b) Write main program code that creates a Patient with ID "P1043", name "Sana Iqbal" and temperature 37.2, then tries to set the temperature to 51.0 and then to 38.5, outputting a suitable message after each attempt. State the output when the program is run. [3]
Show answer
  1. (a) class Patient: def __init__(self, patient_id, name, temperature): self.__patient_id = patient_id # private attributes self.__name = name self.__temperature = temperature def get_patient_id(self): return self.__patient_id def get_name(self): return self.__name def get_temperature(self): return self.__temperature def set_temperature(self, new_temp): if 30.0 <= new_temp <= 45.0: self.__temperature = new_temp return True return False
    1 mark each for: class header; constructor with three parameters (and self in Python); three private attributes assigned (e.g. double underscore in Python); getters returning each attribute (all three for 1 mark); SetTemperature checks 30.0 ≤ NewTemp ≤ 45.0; updates attribute only when valid; returns True/False correctly.
  2. (b) # main programp = Patient("P1043", "Sana Iqbal", 37.2)for reading in [51.0, 38.5]: if p.set_temperature(reading): print("Temperature updated to", p.get_temperature()) else: print("Invalid reading", reading, "- temperature still", p.get_temperature())Output:Invalid reading 51.0 - temperature still 37.2Temperature updated to 38.5
    1 mark: object created with the three values. 1 mark: SetTemperature called for both values and its return value used to choose the message. 1 mark: correct output shown (first rejected, second accepted).
Q7Object-oriented programming · Standard · Paper 3 style · 5 marks
  1. (a) Explain the difference between method overloading and method overriding. [2]
  2. (b) A class Shape has a method Area(). Classes Circle and Rectangle inherit from Shape. A program stores a mixture of Circle and Rectangle objects in one array of type Shape and calls Area() on each element in a loop. Explain how polymorphism makes this possible, and why it is useful. [3]
Show answer
  1. (a) Overloading: several methods in the same class have the same name but different parameter lists (number or types), and the one called depends on the arguments given. Overriding: a subclass redefines a method inherited from its superclass with the same name and parameters.
    1 mark for each correct description.
  2. (b) Each subclass overrides Area() with its own formula. At run time, the version of Area() that runs depends on the actual class of each object, so the same call Area() gives the correct result for every shape. This means the loop does not need IF statements to test the type, and new shapes (e.g. Triangle) can be added without changing the loop.
    1 mark: Area() overridden in each subclass. 1 mark: correct version chosen at run time according to object type. 1 mark: benefit – simpler code / no type checks / easily extended.
Q8Object-oriented programming · Challenge · Paper 3 style · 8 marks
  1. (a) A bank uses this class.CLASS Account PRIVATE AccountNo : STRING PRIVATE Balance : REAL PUBLIC PROCEDURE NEW(GivenNo : STRING) AccountNo ← GivenNo Balance ← 0 ENDPROCEDURE PUBLIC FUNCTION GetBalance() RETURNS REAL RETURN Balance ENDFUNCTION PUBLIC PROCEDURE Deposit(Amount : REAL) Balance ← Balance + Amount ENDPROCEDURE PUBLIC FUNCTION Withdraw(Amount : REAL) RETURNS BOOLEAN IF Amount <= Balance THEN Balance ← Balance - Amount RETURN TRUE ENDIF RETURN FALSE ENDFUNCTIONENDCLASSA class SavingsAccount inherits from Account. It has an extra private attribute WithdrawalsLeft (INTEGER), set to 3 by its constructor. Its Withdraw method overrides the parent's: it allows a withdrawal only if WithdrawalsLeft is greater than 0 and the parent's Withdraw succeeds, and it then reduces WithdrawalsLeft by 1.Write pseudocode for the class SavingsAccount. [7]
  2. (b) Explain why SavingsAccount must call the parent's Withdraw method rather than changing Balance directly. [1]
Show answer
  1. (a) CLASS SavingsAccount INHERITS Account PRIVATE WithdrawalsLeft : INTEGER PUBLIC PROCEDURE NEW(GivenNo : STRING) SUPER.NEW(GivenNo) WithdrawalsLeft ← 3 ENDPROCEDURE PUBLIC FUNCTION Withdraw(Amount : REAL) RETURNS BOOLEAN IF WithdrawalsLeft > 0 THEN IF SUPER.Withdraw(Amount) = TRUE THEN WithdrawalsLeft ← WithdrawalsLeft - 1 RETURN TRUE ENDIF ENDIF RETURN FALSE ENDFUNCTIONENDCLASS
    1 mark each for: CLASS SavingsAccount INHERITS Account … ENDCLASS; PRIVATE WithdrawalsLeft : INTEGER; constructor NEW with GivenNo parameter; SUPER.NEW(GivenNo) called; WithdrawalsLeft ← 3; Withdraw header matching the parent (overriding) and check WithdrawalsLeft > 0; calls SUPER.Withdraw(Amount), decrements WithdrawalsLeft only on success and returns the correct Boolean.
  2. (b) Balance is PRIVATE to Account, so it cannot be accessed directly from the subclass; it can only be changed through Account's public methods.
    B1 Balance is private to Account / encapsulation.
Q9Object-oriented programming · Challenge · Paper 4 style · 13 marks
  1. (a) A ride-hailing app in Karachi calculates fares.• Class Ride has private attributes Rider (string) and Km (integer), a constructor, getters, and a method Fare() that returns 100 + 40 × Km.• Class RickshawRide inherits from Ride. Its Fare() returns 70 + 25 × Km.• Class CarRide inherits from Ride and has an extra private attribute AirCon (Boolean). Its Fare() returns 150 + 55 × Km, increased by 10% if AirCon is True.Write program code for the three classes. (Python shown; Java or VB.NET solutions are equally acceptable.) [9]
  2. (b) Write main program code that stores these objects in one list/array: Ride("Hina", 6), RickshawRide("Omar", 4), CarRide("Zara", 10, True), CarRide("Ali", 3, False). It must output each rider's name and fare, then the total of all fares. State the four fares and the total. [4]
Show answer
  1. (a) class Ride: def __init__(self, rider, km): self.__rider = rider self.__km = km def get_rider(self): return self.__rider def get_km(self): return self.__km def fare(self): return 100 + 40 * self.__kmclass RickshawRide(Ride): def __init__(self, rider, km): super().__init__(rider, km) def fare(self): # overrides Ride.fare return 70 + 25 * self.get_km()class CarRide(Ride): def __init__(self, rider, km, air_con): super().__init__(rider, km) self.__air_con = air_con def fare(self): # overrides Ride.fare cost = 150 + 55 * self.get_km() if self.__air_con: cost = cost * 1.1 return round(cost, 2)
    1 mark each for: Ride class with private Rider and Km; Ride constructor; getters; Ride.Fare correct; RickshawRide declared as a subclass; RickshawRide constructor calls the parent constructor (super); RickshawRide.Fare overrides with 70 + 25 × Km using the getter (Km is private); CarRide subclass with extra private AirCon set in its constructor after calling the parent constructor; CarRide.Fare correct including the 10% increase.
  2. (b) rides = [Ride("Hina", 6), RickshawRide("Omar", 4), CarRide("Zara", 10, True), CarRide("Ali", 3, False)]total = 0for r in rides: print(r.get_rider(), r.fare()) total = total + r.fare()print("Total", round(total, 2))Output: Hina 340, Omar 170, Zara 770.0, Ali 315, Total 1595.0
    1 mark: list/array of the four objects. 1 mark: loop calling Fare() on each object (polymorphism – the correct version is chosen automatically). 1 mark: running total output. 1 mark: correct values 340, 170, 770, 315 and total 1595.
Q10Object-oriented programming · Challenge · Paper 4 style · 12 marks
  1. (a) A cricket league in Quetta needs two classes.• Player: private attributes Name (string) and Runs (integer); a constructor; getters for both attributes.• Team: private attributes TeamName (string) and Players (a list/array of up to 11 Player objects, initially empty); a constructor taking TeamName; a method AddPlayer(P) that adds a Player and returns True, or returns False if the team already has 11 players; a method AverageRuns() that returns the mean runs of the players, rounded to 2 decimal places (0 if there are no players); and a method TopScorer() that returns the name of the player with the most runs.Write program code for both classes. (Python shown; Java or VB.NET solutions are equally acceptable.) [10]
  2. (b) The players Asad 42, Bilal 17, Danish 65, Fahad 8 and Hamza 31 are added to a Team called "Quetta Falcons". State the values returned by AverageRuns() and TopScorer(). [2]
Show answer
  1. (a) class Player: def __init__(self, name, runs): self.__name = name self.__runs = runs def get_name(self): return self.__name def get_runs(self): return self.__runsclass Team: def __init__(self, team_name): self.__team_name = team_name self.__players = [] # a Team contains Player objects def add_player(self, player): if len(self.__players) < 11: self.__players.append(player) return True return False def average_runs(self): if len(self.__players) == 0: return 0 total = 0 for p in self.__players: total = total + p.get_runs() return round(total / len(self.__players), 2) def top_scorer(self): best = self.__players[0] for p in self.__players: if p.get_runs() > best.get_runs(): best = p return best.get_name()
    1 mark each for: Player class with private attributes and constructor; Player getters; Team constructor with TeamName and empty list of players; AddPlayer checks the count against 11; adds the player and returns True / returns False when full; AverageRuns totals runs using GetRuns (not the private attribute directly); divides by the number of players and rounds; handles zero players; TopScorer loops and keeps the best player found so far; returns that player's name.
  2. (b) AverageRuns() returns 32.6; TopScorer() returns "Danish".
    B1 32.6 (163 ÷ 5). B1 Danish.
Q11File processing & exception handling · Core · Paper 3 style · 5 marks
  1. (a) Describe each of these methods of file organisation.(i) serial (ii) sequential (iii) random [3]
  2. (b) Explain the difference between sequential access and direct access. [2]
Show answer
  1. (a) (i) Records are stored one after another in the order in which they were added (chronological), not sorted. (ii) Records are stored one after another in order of a key field. (iii) Records are stored at an address calculated from the key field by a hashing algorithm, so they can be accessed directly.
    1 mark each.
  2. (b) Sequential access reads records one after another from the start of the file until the required record is reached; direct access goes straight to the required record (using its address/index/hash) without reading the earlier records.
    1 mark for each.
Q12File processing & exception handling · Core · Paper 3 style · 5 marks
  1. (a) Explain what is meant by an exception and by exception handling. [2]
  2. (b) Give three situations that could cause an exception in a program that reads data from a file. [3]
Show answer
  1. (a) An exception is an unexpected event/error that occurs while a program is running and would normally cause it to crash (a run-time error). Exception handling is code that detects (catches) the exception and deals with it, so that the program can continue or end tidily.
    1 mark: exception = run-time error/unexpected event. 1 mark: handling = catching it and responding without the program crashing.
  2. (b) Any three of: the file does not exist/wrong name; the file is already in use/no permission; reading past the end of the file; data in the file is the wrong type (e.g. text where a number is expected); disk/drive error or removable drive disconnected; division by zero when processing the data.
    1 mark each for any three.
Q13File processing & exception handling · Core · Paper 3 style · 6 marks
  1. (a) For each application, state the most suitable file organisation (serial, sequential or random) and give a reason.(i) A log of every card swipe at an office door, added in the order they happen.(ii) A monthly payroll file where every employee record is processed in employee-number order.(iii) A bank's ATM system that must find one customer's record very quickly. [6]
Show answer
  1. (a) (i) Serial – records are simply appended in time order and there is no need to sort them. (ii) Sequential – all records are processed in key order in a batch, so storing them in key order is efficient. (iii) Random – direct access using a hash of the account number finds a single record without reading others.
    For each: 1 mark for organisation, 1 mark for a reason.
Q14File processing & exception handling · Standard · Paper 3 style · 6 marks
  1. (a) A courier company stores customer records in a random file with 97 record positions numbered 0 to 96. The address of a record is calculated by: Address ← CustomerID MOD 97.Calculate the address for each customer ID: 4521, 3086, 9311. [3]
  2. (b) A new customer with ID 1611 is added. Explain the problem that occurs and describe one way of dealing with it. [3]
Show answer
  1. (a) 4521 → 59; 3086 → 79; 9311 → 96
    1 mark each.
  2. (b) 1611 MOD 97 = 59, the same address as customer 4521 – a collision. One method: linear probing (open addressing / closed hashing) – look at the next position(s) (60, 61 …) until an empty one is found and store the record there (when searching, start at the hashed address and keep checking the following positions). Alternatively use an overflow area where colliding records are stored and searched serially.
    1 mark: address 59 / same as 4521 – collision. 1 mark: method named (linear probing / overflow area / chaining). 1 mark: method described, including how the record is found later.
Q15File processing & exception handling · Standard · Paper 3 style · 6 marks
  1. (a) A shop stores products in the random file "Stock.dat". Each record has the type:TYPE TProduct DECLARE ProductCode : INTEGER DECLARE Description : STRING DECLARE Quantity : INTEGERENDTYPEThe record for a product is stored at the address given by the function Hash(ProductCode) (assume there are no collisions).Write a pseudocode procedure UpdateStock(Code : INTEGER, Sold : INTEGER) that finds the record for the product, reduces its Quantity by Sold, and writes the record back to the file. [6]
Show answer
  1. (a) PROCEDURE UpdateStock(Code : INTEGER, Sold : INTEGER) DECLARE ThisProduct : TProduct DECLARE Address : INTEGER Address ← Hash(Code) OPENFILE "Stock.dat" FOR RANDOM SEEK "Stock.dat", Address GETRECORD "Stock.dat", ThisProduct ThisProduct.Quantity ← ThisProduct.Quantity - Sold SEEK "Stock.dat", Address PUTRECORD "Stock.dat", ThisProduct CLOSEFILE "Stock.dat"ENDPROCEDURE
    1 mark each for: declare a variable of type TProduct; Address calculated with Hash(Code); OPENFILE … FOR RANDOM; SEEK to the address then GETRECORD into the variable; update the Quantity field using dot notation; SEEK again, PUTRECORD and CLOSEFILE.
Q16File processing & exception handling · Standard · Paper 4 style · 9 marks
  1. (a) The text file Scores.txt contains one integer score per line:678245917358Write a function ReadScores(FileName) that reads all the scores from the file into a list/array and returns it. It must use exception handling so that, if the file does not exist, a message is output and an empty list is returned instead of the program crashing. (Python shown; Java or VB.NET solutions are equally acceptable.) [6]
  2. (b) Write main program code that calls ReadScores("Scores.txt") and outputs the highest score and the mean score rounded to 1 decimal place. State the output. [3]
Show answer
  1. (a) def read_scores(filename): scores = [] try: file = open(filename, "r") for line in file: line = line.strip() if line != "": scores.append(int(line)) file.close() except FileNotFoundError: print("File", filename, "not found") return scores
    1 mark each for: function header with the file name as a parameter; opens the file for reading; loops through every line until end of file; converts each line to an integer and adds it to the list; closes the file and returns the list; try/except catching the file-not-found exception with a message (and returning an empty list).
  2. (b) scores = read_scores("Scores.txt")if len(scores) > 0: print("Highest:", max(scores)) print("Average:", round(sum(scores) / len(scores), 1))Output:Highest: 91Average: 69.3
    1 mark: function called and result stored. 1 mark: highest and mean calculated (check list not empty). 1 mark: correct output 91 and 69.3.
Q17File processing & exception handling · Standard · Paper 4 style · 10 marks
  1. (a) A sports club stores members in the text file Members.txt, one member per line in the form ID,Name,City.Write:• a procedure SaveMember(FileName, MemberID, Name, City) that adds one member to the end of the file• a function FindMember(FileName, MemberID) that returns the member's name and city in the form Name (City), returns "Not found" if there is no such ID, and returns "No member file" if the file does not exist (use exception handling). (Python shown; Java or VB.NET solutions are equally acceptable.) [7]
  2. (b) Starting with no Members.txt file, a program calls FindMember for "M01", saves M01 Nida Rauf Sukkur and M02 Kamran Ali Mardan, then calls FindMember for "M02" and for "M07". State the three values returned. [3]
Show answer
  1. (a) def save_member(filename, member_id, name, city): file = open(filename, "a") file.write(member_id + "," + name + "," + city + "\n") file.close()def find_member(filename, member_id): try: file = open(filename, "r") except FileNotFoundError: return "No member file" for line in file: fields = line.strip().split(",") if fields[0] == member_id: file.close() return fields[1] + " (" + fields[2] + ")" file.close() return "Not found"
    1 mark each for: file opened in append mode in SaveMember; one line written with commas and a newline, file closed; FindMember opens the file for reading inside try/except; returns "No member file" in the handler; loops through lines splitting on commas; compares the first field with MemberID and returns Name (City); returns "Not found" after the loop (file closed).
  2. (b) "No member file", "Kamran Ali (Mardan)", "Not found"
    1 mark each.
Q18File processing & exception handling · Challenge · Paper 3 style · 7 marks
  1. (a) A sequential file "Members.txt" holds club member records in ascending order of MemberID. Describe, without writing pseudocode, the steps needed to add one new member record so that the file stays in order. [5]
  2. (b) Explain why adding records is quicker for a random file than for a sequential file. [2]
Show answer
  1. (a) Open Members.txt for reading and a new (temporary) file for writing. Read each record in turn from the old file. While the MemberID read is less than the new MemberID, write the record to the new file. When the first record with a larger ID is reached (and the new record has not yet been written), write the new record and then that record. Copy all remaining records. If the end of the old file is reached without writing the new record, write it at the end. Close both files, then delete/rename so the new file replaces the old one.
    1 mark each for any five of: open old file for read and new file for write; read records one at a time until end of file; copy records with smaller key; insert new record at the correct position (before first larger key); copy remaining records; handle new record belonging at the end; close both files; replace old file with new file.
  2. (b) In a random file the address is calculated from the key, so the record is written straight to that position; a sequential file must be copied record by record to a new file to keep it in order.
    1 mark: random – direct write to hashed address. 1 mark: sequential – whole file has to be read/copied.
Q19File processing & exception handling · Challenge · Paper 4 style · 13 marks
  1. (a) Weather stations send readings that are stored in Readings.txt, one per line in the form station,temperature. Some lines are damaged. The file contains:Gilgit,4.5Multan,38.2Gilgit,abcMultan,41.0Skardu,-2.5MultanGilgit,6.1Skardu,1.5Write a procedure ProcessReadings(FileName) that:• reads every line of the file• uses exception handling to count a line as invalid if it does not have exactly two fields or the temperature is not a number, and continues with the next line• outputs the number of valid and invalid lines• outputs, for each station in alphabetical order, the mean of its valid temperatures rounded to 2 decimal places• outputs a message (and stops) if the file cannot be opened. (Python shown; Java or VB.NET solutions are equally acceptable.) [10]
  2. (b) State the output when ProcessReadings("Readings.txt") is called with the file shown. [3]
Show answer
  1. (a) def process_readings(filename): totals = {} counts = {} valid = 0 invalid = 0 try: file = open(filename, "r") except FileNotFoundError: print("Cannot open", filename) return for line in file: try: station, value = line.strip().split(",") temp = float(value) totals[station] = totals.get(station, 0) + temp counts[station] = counts.get(station, 0) + 1 valid = valid + 1 except ValueError: # wrong number of fields or not a number invalid = invalid + 1 file.close() print("Valid:", valid, "Invalid:", invalid) for station in sorted(totals): print(station, round(totals[station] / counts[station], 2))
    1 mark each for: procedure header with parameter; file opened inside a try with a file-not-found handler that outputs a message; loop through every line; split into fields; conversion to real/float; exception for a bad line caught inside the loop so processing continues; invalid counter incremented in the handler; totals and counts kept per station (e.g. dictionary or parallel arrays); valid count output with invalid count; means output per station in alphabetical order, rounded to 2 d.p.
  2. (b) Valid: 6 Invalid: 2Gilgit 5.3Multan 39.6Skardu -0.5
    1 mark: 6 valid and 2 invalid ('Gilgit,abc' and 'Multan'). 1 mark: Gilgit 5.3 and Multan 39.6. 1 mark: Skardu −0.5.
Q20File processing & exception handling · Challenge · Paper 3 style · 6 marks
  1. (a) A hash table has 11 positions (0 to 10). The hash function is Key MOD 11. Collisions are handled by storing the record in the next free position (wrapping from 10 to 0). The keys 35, 62, 18, 46, 100, 24 and 53 are inserted in that order into an empty table. State the position of each key. [4]
  2. (b) State how many positions must be examined to find key 24, and how many to decide that key 57 is not in the table. [2]
Show answer
  1. (a) 35 → 2, 62 → 7, 18 → 8, 46 → 3, 100 → 1, 24 → 4, 53 → 9
    Hash values: 35→2, 62→7, 18→7 (taken, so 8), 46→2 (taken, so 3), 100→1, 24→2 (2 and 3 taken, so 4), 53→9. 4 marks all correct; 3 marks for 6 correct; 2 marks for 5; 1 mark for 3–4.
  2. (b) 24: 3 positions (2, 3, 4). 57: 4 positions (2, 3, 4, 5 – stop at the empty position 5).
    1 mark each.
Q21Declarative programming (Prolog) · Core · Paper 3 style · 5 marks

A Prolog knowledge base contains these facts about direct flights (flight(A, B) means there is a flight from A to B):flight(karachi, lahore).flight(lahore, islamabad).flight(karachi, quetta).flight(islamabad, gilgit).flight(lahore, skardu).

  1. (a) State the result(s) of each goal, in the order Prolog finds them.(i) flight(lahore, X).(ii) flight(X, gilgit).(iii) flight(quetta, Y). [3]
  2. (b) Write a fact to show that there is a flight from Quetta to Islamabad. [1]
  3. (c) Write a goal to find every city that has a direct flight from Karachi. [1]
Show answer
  1. (a) (i) X = islamabad; X = skardu (ii) X = islamabad (iii) false (no results)
    1 mark each; (i) needs both in this order.
  2. (b) flight(quetta, islamabad).
    B1 (lower-case constants, full stop).
  3. (c) flight(karachi, City).
    B1 any variable starting with an upper-case letter.
Q22Declarative programming (Prolog) · Core · Paper 3 style · 7 marks
  1. (a) Write Prolog facts to represent this information.• Nadia speaks Urdu.• Nadia speaks English.• Tariq speaks Pashto.• Tariq speaks Urdu.• Mei speaks Mandarin. [3]
  2. (b) Write a goal to find everyone who speaks Urdu, and state its results. [2]
  3. (c) Write a rule can_talk(X, Y) that is true if X and Y are different people who share a language. [2]
Show answer
  1. (a) speaks(nadia, urdu).speaks(nadia, english).speaks(tariq, pashto).speaks(tariq, urdu).speaks(mei, mandarin).
    1 mark: consistent predicate with two arguments. 1 mark: constants in lower case. 1 mark: all five facts correct with full stops.
  2. (b) speaks(Person, urdu). Results: Person = nadia; Person = tariq
    1 mark: goal with variable in first argument. 1 mark: both results.
  3. (c) can_talk(X, Y) :- speaks(X, L), speaks(Y, L), X \= Y.
    1 mark: shared variable L. 1 mark: X \= Y (or NOT(X = Y)).
Q23Declarative programming (Prolog) · Standard · Paper 3 style · 5 marks

A Prolog knowledge base about direct train services (train(A, B) means a train runs from A to B):train(peshawar, rawalpindi).train(rawalpindi, lahore).train(lahore, multan).train(lahore, faisalabad).train(multan, karachi).

  1. (a) Write a rule one_change(X, Z) that is true if a passenger can travel from X to Z using exactly two trains (changing once at some station Y). [2]
  2. (b) Using your rule, state the results of these goals in the order Prolog finds them.(i) one_change(rawalpindi, Z).(ii) one_change(X, karachi). [3]
Show answer
  1. (a) one_change(X, Z) :- train(X, Y), train(Y, Z).
    1 mark: head one_change(X, Z) and :-. 1 mark: body with two train facts sharing variable Y.
  2. (b) (i) Z = multan; Z = faisalabad (ii) X = lahore
    2 marks for (i) (1 mark each, in order); 1 mark for (ii).
Q24Declarative programming (Prolog) · Standard · Paper 3 style · 7 marks

A canteen uses this Prolog knowledge base:contains(biryani, rice).contains(biryani, chicken).contains(halwa, semolina).contains(halwa, nuts).contains(kheer, rice).contains(kheer, milk).contains(kheer, nuts).allergic(sara, nuts).allergic(usman, milk).cannot_eat(P, D) :- allergic(P, I), contains(D, I).

  1. (a) State the results of the goal cannot_eat(sara, D). [2]
  2. (b) Explain, using this goal, what is meant by instantiation and backtracking. [4]
  3. (c) Write a goal to find all the dishes that Usman cannot eat, and state its result. [1]
Show answer
  1. (a) D = halwa; D = kheer
    1 mark each.
  2. (b) Instantiation: a variable is given (bound to) a value when a match is found – e.g. I is instantiated to nuts from allergic(sara, nuts), then D to halwa. Backtracking: after a solution is found (or a sub-goal fails), Prolog goes back to the most recent choice point and tries the next possible match – e.g. it returns to contains(D, nuts) and finds contains(kheer, nuts), giving D = kheer.
    1 mark: instantiation definition. 1 mark: instantiation example from the goal. 1 mark: backtracking definition. 1 mark: backtracking example.
  3. (c) cannot_eat(usman, D). Result: D = kheer
    B1 goal and result.
Q25Declarative programming (Prolog) · Standard · Paper 3 style · 5 marks
  1. (a) Describe two features of declarative programming that make it different from imperative programming. [4]
  2. (b) Suggest one type of application for which declarative programming is well suited. [1]
Show answer
  1. (a) In declarative programming the programmer states facts and rules describing the problem (what is true), not the step-by-step method; the language's inference engine searches the knowledge base (with backtracking) to find solutions to goals. In imperative programming the programmer writes a sequence of instructions that change the program's state (variables) step by step.
    For each of two features: 1 mark for the feature, 1 mark for the contrast with imperative programming (e.g. facts/rules vs sequence of commands; goal-directed search/backtracking vs explicit control flow; no assignment/state change vs variables updated).
  2. (b) Expert systems / knowledge-based systems / natural language processing / AI problems such as route-finding or puzzles.
    B1.
Q26Declarative programming (Prolog) · Challenge · Paper 3 style · 8 marks

A family tree is stored in Prolog:parent(rashid, sana).parent(rashid, imran).parent(sana, ali).parent(ali, zoya).parent(imran, hira).ancestor(X, Y) :- parent(X, Y).ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).

  1. (a) State all the results of the goal ancestor(rashid, Y), in the order Prolog finds them. [3]
  2. (b) Identify the base case and the general (recursive) case in the definition of ancestor, and explain why the base case is needed. [3]
  3. (c) Write a rule cousin(X, Y) that is true if X and Y are different people whose parents are siblings (two different children of the same parent). [2]
Show answer
  1. (a) Y = sana; Y = imran; Y = ali; Y = zoya; Y = hira
    1 mark: sana, imran first (from the first clause). 1 mark: ali, zoya, hira all present. 1 mark: correct order. (Second clause: Z = sana gives ali then, recursively, zoya; Z = imran gives hira.)
  2. (b) Base case: ancestor(X, Y) :- parent(X, Y). General case: ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y). The base case stops the recursion: without it, the rule would keep calling itself and never succeed (infinite recursion).
    1 mark each.
  3. (c) cousin(X, Y) :- parent(PX, X), parent(PY, Y), parent(G, PX), parent(G, PY), PX \= PY, X \= Y.
    1 mark: X and Y's parents found with a shared grandparent G. 1 mark: PX and PY must be different (\= or NOT(PX = PY)).
Q27Declarative programming (Prolog) · Challenge · Paper 3 style · 7 marks

A Prolog program stores students' ages:age(asma, 17).age(bilal, 19).age(chen, 16).age(david, 21).older(X, Y) :- age(X, A), age(Y, B), A > B.can_vote(X) :- age(X, A), A >= 18.

  1. (a) State the results of each goal.(i) can_vote(X).(ii) older(X, bilal).(iii) older(chen, X). [3]
  2. (b) State how many solutions Prolog finds for the goal older(X, Y). Explain your answer. [2]
  3. (c) Write a rule teenager(X) that is true if X is aged from 13 to 19 inclusive. [2]
Show answer
  1. (a) (i) X = bilal; X = david (ii) X = david (iii) false
    1 mark each.
  2. (b) 6. Every pair of different people with different ages gives exactly one solution (the older first); all four ages are different, so the number of pairs is 4 × 3 ÷ 2 = 6.
    1 mark: 6. 1 mark: explanation (each unordered pair once, since ages are all different).
  3. (c) teenager(X) :- age(X, A), A >= 13, A =< 19.
    1 mark: age(X, A) in body. 1 mark: both comparisons correct (=< in Prolog).
Q28Programming paradigms & low-level programming · Core · Paper 3 style · 4 marks
  1. (a) Describe the main characteristic of each programming paradigm.(i) low-level (ii) imperative (procedural) (iii) object-oriented (iv) declarative [4]
Show answer
  1. (a) (i) Instructions closely match the processor's instruction set (assembly/machine code), working directly with registers and memory addresses. (ii) The program is a sequence of statements that change the program's state, organised into procedures and functions. (iii) The program is built from objects (instances of classes) that combine data and methods, using encapsulation, inheritance and polymorphism. (iv) The program states facts and rules; the system works out how to reach a goal.
    1 mark each.
Q29Programming paradigms & low-level programming · Standard · Paper 3 style · 6 marks
  1. (a) The program below uses the instruction set: LDR #n (load n into the index register IX), LDM #n (load n into ACC), LDD <address> (load contents of address into ACC), LDX <address> (load contents of (address + IX) into ACC), ADD <address> (add contents of address to ACC), STO <address> (store ACC at address), INC IX / DEC ACC (add/subtract 1), CMP #n (compare ACC with n), JPN <address> (jump if the comparison was not equal), END.100 LDR #0101 LDM #0102 STO 210103 LDX 200104 ADD 210105 STO 210106 INC IX107 LDD 211108 DEC ACC109 STO 211110 CMP #0111 JPN 103112 ENDMemory before running: address 200 = 12, 201 = 7, 202 = 25, 203 = 9, 211 = 4.State the contents of address 210, address 211 and IX when the program ends, and the number of times the instruction at address 103 is executed. [4]
  2. (b) Name the addressing mode used by the instruction at address 103 and explain why it is useful in this program. [2]
Show answer
  1. (a) Address 210 = 53; address 211 = 0; IX = 4; instruction 103 executed 4 times.
    1 mark each. 210 holds 12 + 7 + 25 + 9 = 53.
  2. (b) Indexed addressing. The address used is 200 + IX, and IX is increased each time round the loop, so the same instruction reads a different array element (200, 201, 202, 203) on each pass.
    1 mark: indexed. 1 mark: IX changes so same instruction accesses successive locations in a loop.
Q30Programming paradigms & low-level programming · Challenge · Paper 3 style · 8 marks
  1. (a) Using the instruction set below, write a low-level program that counts how many of the five values stored at addresses 300 to 304 are equal to the value stored at address 310. Store the count at address 311 (it starts at 0). Address 312 holds 5, the number of values to check.Instructions: LDR #n, LDM #n, LDD <address>, LDX <address> (loads contents of address + IX), STO <address>, ADD <address>, INC <register>, DEC <register> (register is ACC or IX), CMP <address> (compare ACC with contents of address), CMP #n, JPE <address>, JPN <address>, JMP <address>, END.Start your program at address 50. [7]
  2. (b) Memory holds 300 = 4, 301 = 9, 302 = 4, 303 = 2, 304 = 4 and 310 = 4. State the value stored at address 311 when your program ends. [1]
Show answer
  1. (a) 50 LDR #051 LDX 30052 CMP 31053 JPN 5754 LDD 31155 INC ACC56 STO 31157 INC IX58 LDD 31259 DEC ACC60 STO 31261 CMP #062 JPN 5163 END
    1 mark each for: IX initialised to 0; LDX 300 to load the current value; CMP 310 and conditional jump to skip when not equal; count loaded, incremented and stored back at 311; IX incremented; loop counter at 312 decremented and stored; compare with 0 and jump back to the loop start, END after the loop. (Accept equivalent working programs.)
  2. (b) 3
    B1.

Similar questions

Questions that test the same subtopic in different years, grouped so you can work on one skill at a time.

References only: find each question in its paper (official link where available, otherwise through your school).

Object-oriented programming 6 questions · 6/9 sessions
File processing & exception handling 6 questions · 6/9 sessions
Declarative programming (Prolog) 3 questions · 3/9 sessions

Subtopics

Our analysis of how often each subtopic was examined and how many marks it carried, 2022 to May/June 2026.

SubtopicMarks indexedSessions
Object-oriented programming 366/9
File processing & exception handling 336/9
Declarative programming (Prolog) 253/9
Programming paradigms & low-level programming Rare71/9

← All Computer Science topics