Question Simulator

AS & A Level Computer Science (9618)

Data types and structures Banker

32 questions · about 10% of the marks we indexed · examined in 9 of 9 sessions.

Questions by year

2026

  • 2026 May/June · Paper 22 · Q1 (a(i))1 markData types & records
  • 2026 May/June · Paper 22 · Q36 marksText files
  • 2026 May/June · Paper 22 · Q4 (a, b)9 marksStacks, queues & linked lists
  • 2026 May/June · Paper 22 · Q6 (b(i), b(ii))10 marksArrays

2025

  • 2025 Oct/Nov · Paper 22 · Q1 (b)3 marksData types & records
  • 2025 Oct/Nov · Paper 22 · Q25 marksArrays
  • 2025 Oct/Nov · Paper 22 · Q3 (a, b, c)10 marksText files
  • 2025 Oct/Nov · Paper 22 · Q4 (a)4 marksArrays
  • 2025 Oct/Nov · Paper 22 · Q8 (c, d)4 marksData types & records · Text files
  • 2025 May/June · Paper 22 · Q1 (c, d(i), d(ii), d(iii))8 marksArrays · Data types & records
  • 2025 May/June · Paper 22 · Q46 marksArrays
  • 2025 May/June · Paper 22 · Q6 (a(ii), b)5 marksStacks, queues & linked lists
  • 2025 May/June · Paper 22 · Q7 (c(i), c(ii))3 marksArrays

2024

  • 2024 Oct/Nov · Paper 22 · Q1 (d)3 marksData types & records
  • 2024 Oct/Nov · Paper 22 · Q2 (b(i))2 marksArrays
  • 2024 Oct/Nov · Paper 22 · Q3 (a(i), a(ii), b)7 marksStacks, queues & linked lists
  • 2024 Oct/Nov · Paper 22 · Q8 (b, c, d)11 marksData types & records · Text files
  • 2024 May/June · Paper 22 · Q1 (b)4 marksData types & records
  • 2024 May/June · Paper 22 · Q3 (a(i), a(ii), b)9 marksArrays · Data types & records
  • 2024 May/June · Paper 22 · Q6 (b(i), b(ii), b(iii))3 marksData types & records
  • 2024 May/June · Paper 22 · Q8 (c)8 marksText files

2023

  • 2023 Oct/Nov · Paper 22 · Q1 (c)3 marksData types & records
  • 2023 Oct/Nov · Paper 22 · Q3 (a, b)9 marksStacks, queues & linked lists
  • 2023 Oct/Nov · Paper 22 · Q6 (a, b(iii))7 marksText files
  • 2023 Oct/Nov · Paper 22 · Q8 (c(i), c(ii))4 marksStacks, queues & linked lists
  • 2023 May/June · Paper 22 · Q1 (a(i), a(ii), c)7 marksArrays · Data types & records
  • 2023 May/June · Paper 22 · Q3 (a(i), a(ii), b)10 marksStacks, queues & linked lists
  • 2023 May/June · Paper 22 · Q8 (b)7 marksText files

2022

  • 2022 Oct/Nov · Paper 22 · Q2 (a(i), a(ii), a(iii))7 marksText files
  • 2022 Oct/Nov · Paper 22 · Q3 (a, b, c)13 marksStacks, queues & linked lists
  • 2022 Oct/Nov · Paper 22 · Q7 (c(i), c(ii), c(iii))4 marksData types & records
  • 2022 May/June · Paper 22 · Q4 (a, b)9 marksText files

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.

Q1Text files · Core · Paper 2 style · 4 marks
  1. (a) State the purpose of each file mode: READ, WRITE, APPEND. [3]
  2. (b) Explain why a program should always close a file after use. [1]
Show answer
  1. (a) READ – data can only be read from an existing file.WRITE – creates a new file (or overwrites an existing one) and writes data to it.APPEND – adds new data to the end of an existing file, keeping its current contents.
    1 mark each.
  2. (b) To make sure all data is written / saved to the file and the file is released for other programs (or for reopening in another mode).
    B1.
Q2Text files · Core · Paper 2 style · 5 marks

A school in Sukkur stores each student's name on a separate line of a text file.

  1. (a) Write pseudocode for the procedure CountLines(FileName : STRING), which outputs the number of lines in the text file whose name is passed as the parameter. [5]
Show answer
  1. (a) PROCEDURE CountLines(FileName : STRING) DECLARE Line : STRING DECLARE Count : INTEGER Count ← 0 OPENFILE FileName FOR READ WHILE NOT EOF(FileName) READFILE FileName, Line Count ← Count + 1 ENDWHILE CLOSEFILE FileName OUTPUT "Number of lines: ", CountENDPROCEDURE
    1 mark each:• Count initialised to 0 before the loop• file opened FOR READ using the parameter (not in quotes)• conditional loop until EOF(FileName)• READFILE inside loop and Count incremented• CLOSEFILE FileName after the loop and Count outputLENGTH() cannot be used to count lines.
Q3Text files · Core · Paper 2 style · 4 marks

A programmer writes this procedure to output every line of a text file:01 PROCEDURE ShowFile(FileName : STRING)02 DECLARE Line : STRING03 OPENFILE "FileName"04 FOR Count ← 1 TO EOF(FileName)05 READFILE FileName, Line06 OUTPUT Line07 NEXT Count08 CLOSEFILE09 ENDPROCEDURE

  1. (a) Identify four errors in the pseudocode and give the correction for each. [4]
Show answer
  1. (a) Line 03: the parameter is in quotes — should be OPENFILE FileName …Line 03: no file mode — should be OPENFILE FileName FOR READLine 04: a FOR loop cannot run TO EOF — use WHILE NOT EOF(FileName) (with ENDWHILE replacing NEXT Count on line 07)Line 08: CLOSEFILE has no file identifier — should be CLOSEFILE FileName
    1 mark each error with a correct correction.
Q4Text files · Standard · Paper 2 style · 7 marks

The text file Results.txt contains these six lines:Ali,72Fatima,58Usman,91Hina,64Bilal,45Zara,80This algorithm processes the file:DECLARE Line : STRINGDECLARE Count, Total, Mark, Pos : INTEGERCount ← 0Total ← 0OPENFILE "Results.txt" FOR READWHILE NOT EOF("Results.txt") READFILE "Results.txt", Line Pos ← 1 WHILE MID(Line, Pos, 1) <> ',' Pos ← Pos + 1 ENDWHILE Mark ← STR_TO_NUM(RIGHT(Line, LENGTH(Line) - Pos)) IF Mark >= 60 THEN Count ← Count + 1 Total ← Total + Mark ENDIFENDWHILECLOSEFILE "Results.txt"OUTPUT Count, " ", Total

  1. (a) State the output when the algorithm is run. [2]
  2. (b) State the value of Pos after the inner loop has finished for the last line in the file. [1]
  3. (c) Explain the purpose of the expression RIGHT(Line, LENGTH(Line) - Pos). [2]
  4. (d) Write the pseudocode statement(s) to replace the final OUTPUT so that the average of the counted marks is output. The program must not divide by zero. [2]
Show answer
  1. (a) 4 307
    Marks ≥ 60 are 72, 91, 64, 80. B1 Count = 4; B1 Total = 307.
  2. (b) 5
    In "Zara,80" the comma is the 5th character.
  3. (c) It extracts all the characters after the comma, i.e. the mark (as a string), so that STR_TO_NUM can convert it to a number.
    1 mark characters after the comma; 1 mark this is the mark, converted to a number.
  4. (d) IF Count > 0 THEN OUTPUT Total / CountELSE OUTPUT "No marks of 60 or more"ENDIF
    1 mark Total / Count output; 1 mark check Count > 0.
Q5Text files · Standard · Paper 2 style · 6 marks

A cricket club in Sialkot keeps a text file of members' names, one name per line.

  1. (a) Write pseudocode for the function IsMember(FileName : STRING, SearchName : STRING) RETURNS BOOLEAN. The function returns TRUE if any line of the file matches SearchName, ignoring upper/lower case, and FALSE otherwise. The search must stop as soon as a match is found. [6]
Show answer
  1. (a) FUNCTION IsMember(FileName : STRING, SearchName : STRING) RETURNS BOOLEAN DECLARE Line : STRING DECLARE Found : BOOLEAN Found ← FALSE OPENFILE FileName FOR READ WHILE NOT EOF(FileName) AND Found = FALSE READFILE FileName, Line IF TO_UPPER(Line) = TO_UPPER(SearchName) THEN Found ← TRUE ENDIF ENDWHILE CLOSEFILE FileName RETURN FoundENDFUNCTION
    1 mark each:• function header and Found initialised to FALSE• OPENFILE FileName FOR READ• loop that stops at EOF or when found• READFILE inside the loop• case-insensitive comparison (TO_UPPER/TO_LOWER on both)• CLOSEFILE and RETURN Found (after closing)
Q6Text files · Standard · Paper 2 style · 7 marks

A travel company in Lahore stores the names of destination cities in a global 1D array Cities[1:50] OF STRING. Unused elements contain an empty string "".

  1. (a) Write pseudocode for the procedure SaveCities(), which writes every element of Cities that is not an empty string to the file Cities.txt, one city per line. [5]
  2. (b) State what happens to the existing contents of Cities.txt when the procedure runs. [1]
  3. (c) State the change needed so that the cities are added after the existing contents instead. [1]
Show answer
  1. (a) PROCEDURE SaveCities() DECLARE Index : INTEGER OPENFILE "Cities.txt" FOR WRITE FOR Index ← 1 TO 50 IF Cities[Index] <> "" THEN WRITEFILE "Cities.txt", Cities[Index] ENDIF NEXT Index CLOSEFILE "Cities.txt"ENDPROCEDURE
    1 mark each:• open Cities.txt FOR WRITE (before the loop)• FOR loop 1 to 50• test for empty string• WRITEFILE of the element• CLOSEFILE after the loop
  2. (b) They are lost / overwritten, because opening FOR WRITE creates a new file.
    B1.
  3. (c) Open the file FOR APPEND instead of FOR WRITE.
    B1.
Q7Text files · Standard · Paper 4 style · 8 marks

A weather station in Jacobabad stores daily maximum temperatures in the text file temps.txt, one real number per line.

  1. (a) Write program code for a function summarise(filename) that:• opens the text file and reads every reading (ignoring blank lines)• calculates the number of readings, the average (rounded to 1 decimal place) and the highest reading• writes these three results to a new file summary.txt on three lines• returns the three values• outputs "File not found" and returns nothing if the file does not exist.Write a main program that calls the function with temps.txt and outputs the result. [8]
Show answer
  1. (a) def summarise(filename): try: f = open(filename, "r") except FileNotFoundError: print("File not found") return None count = 0 total = 0.0 highest = None for line in f: line = line.strip() if line != "": value = float(line) count += 1 total += value if highest is None or value > highest: highest = value f.close() if count == 0: print("No readings") return None average = round(total / count, 1) out = open("summary.txt", "w") out.write("Readings: " + str(count) + "\n") out.write("Average: " + str(average) + "\n") out.write("Highest: " + str(highest) + "\n") out.close() return count, average, highest# main programresult = summarise("temps.txt")print(result)(Java or VB.NET solutions with the same logic are equally acceptable.)Test run with temps.txt containing 31.5, 29.0, (blank line), 34.2, 36.8, 33.0 outputs (5, 32.9, 36.8), and summary.txt contains:Readings: 5Average: 32.9Highest: 36.8With temps.txt missing it outputs: File not found
    1 mark each, max 8:• file opened for reading inside exception handling / existence check• "File not found" output and function ends when missing• loop through every line• blank lines skipped and each line converted to a real number• count and total updated• highest found correctly (initialised from first value or very low value)• average calculated and rounded to 1 d.p.• summary.txt opened for writing, three lines written, both files closed• values returned and main program calls and outputs
Q8Text files · Challenge · Paper 2 style · 8 marks

A grocery wholesaler in Gujranwala stores its stock in the text file Stock.txt. Each line holds a 6-character item code followed immediately by the quantity in stock, for example:RICE05150SUGR0112DAAL098The first line means item RICE05 has 150 units in stock.

  1. (a) Write pseudocode for the function MakeReorderList(Threshold : INTEGER) RETURNS INTEGER.The function must:• read every line of Stock.txt• write the item code of each item whose quantity is less than Threshold to a new file Reorder.txt, one code per line• return the number of item codes written. [8]
Show answer
  1. (a) FUNCTION MakeReorderList(Threshold : INTEGER) RETURNS INTEGER DECLARE Line, ItemCode : STRING DECLARE Quantity, Count : INTEGER Count ← 0 OPENFILE "Stock.txt" FOR READ OPENFILE "Reorder.txt" FOR WRITE WHILE NOT EOF("Stock.txt") READFILE "Stock.txt", Line ItemCode ← LEFT(Line, 6) Quantity ← STR_TO_NUM(RIGHT(Line, LENGTH(Line) - 6)) IF Quantity < Threshold THEN WRITEFILE "Reorder.txt", ItemCode Count ← Count + 1 ENDIF ENDWHILE CLOSEFILE "Stock.txt" CLOSEFILE "Reorder.txt" RETURN CountENDFUNCTION
    1 mark each, max 8:• Count initialised• Stock.txt opened FOR READ• Reorder.txt opened FOR WRITE• loop until EOF of Stock.txt with READFILE inside• item code extracted with LEFT(Line, 6) (or MID(Line, 1, 6))• quantity extracted from character 7 onwards and converted with STR_TO_NUM• compare with Threshold, WRITEFILE item code and increment Count• both files closed• Count returned (after files closed)
Q9Text files · Challenge · Paper 2 style · 7 marks

A solar inverter in a house in Quetta records events in a text file Log.txt.

  1. (a) Write pseudocode for the function AddLogEntry(Message : STRING) RETURNS INTEGER.Each line of Log.txt has the form <line number>: <message>, for example "7: Battery full". The function must find how many lines the file already contains, add a new line to the end of the file with the next line number and the message, and return the new line number. You may assume Log.txt already exists. [7]
Show answer
  1. (a) FUNCTION AddLogEntry(Message : STRING) RETURNS INTEGER DECLARE Line : STRING DECLARE Count : INTEGER Count ← 0 OPENFILE "Log.txt" FOR READ WHILE NOT EOF("Log.txt") READFILE "Log.txt", Line Count ← Count + 1 ENDWHILE CLOSEFILE "Log.txt" Count ← Count + 1 OPENFILE "Log.txt" FOR APPEND WRITEFILE "Log.txt", NUM_TO_STR(Count) & ": " & Message CLOSEFILE "Log.txt" RETURN CountENDFUNCTION
    1 mark each:• Count initialised; file opened FOR READ• loop to EOF reading each line and counting• file closed before reopening• next line number calculated (Count + 1)• file reopened FOR APPEND• line built with NUM_TO_STR, ": " and Message using & and written with WRITEFILE• file closed and new number returned
Q10Stacks, queues & linked lists · Core · Paper 2 style · 5 marks

A stack is implemented with the 1D array Stack[1:8] OF INTEGER and the pointer TopOfStack, which holds the index of the top item. Initially the stack is empty and TopOfStack = 0.These operations are carried out in order:PUSH 15, PUSH 8, PUSH 23, POP, PUSH 4, PUSH 19, POP, POP, PUSH 30

  1. (a) State the values removed by the POP operations, in the order they are removed. [1]
  2. (b) State the final value of TopOfStack and the contents of Stack[1] to Stack[TopOfStack]. [2]
  3. (c) State the value stored in the array element Stack[4] after all the operations. Explain your answer. [2]
Show answer
  1. (a) 23, 19, 4
    B1 all three in order.
  2. (b) TopOfStack = 3; Stack[1] = 15, Stack[2] = 8, Stack[3] = 30
    1 mark TopOfStack; 1 mark contents.
  3. (c) 19 — popping only moves TopOfStack down; the value is not deleted from the array, but it is no longer part of the stack.
    1 mark value; 1 mark explanation.
Q11Stacks, queues & linked lists · Core · Paper 2 style · 4 marks
  1. (a) Describe the difference between a stack and a queue. [2]
  2. (b) Give one use of a stack and one use of a queue in a computer system. [2]
Show answer
  1. (a) A stack is LIFO — the last item added is the first removed, and items are added/removed at the same end (top). A queue is FIFO — items are added at the rear and removed from the front.
    1 mark each.
  2. (b) Stack: e.g. storing return addresses for procedure calls / undo feature / evaluating expressions. Queue: e.g. print jobs waiting / keyboard buffer / processes waiting for the CPU.
    1 mark each.
Q12Stacks, queues & linked lists · Standard · Paper 2 style · 8 marks

A text editor stores codes for the user's recent actions so they can be undone. It uses a stack held in the global array UndoStack[1:50] OF INTEGER with the global pointer TopOfStack, initialised to 0 (empty).

  1. (a) Write pseudocode for the function Push(Action : INTEGER) RETURNS BOOLEAN, which adds Action to the stack. It returns FALSE if the stack is full, otherwise TRUE. [4]
  2. (b) Write pseudocode for the function Pop() RETURNS INTEGER, which removes and returns the top item. It returns −1 if the stack is empty. [4]
Show answer
  1. (a) FUNCTION Push(Action : INTEGER) RETURNS BOOLEAN IF TopOfStack = 50 THEN RETURN FALSE ELSE TopOfStack ← TopOfStack + 1 UndoStack[TopOfStack] ← Action RETURN TRUE ENDIFENDFUNCTION
    1 mark check for full (TopOfStack = 50); 1 mark increment TopOfStack; 1 mark store at new top (in that order); 1 mark correct BOOLEAN returns.
  2. (b) FUNCTION Pop() RETURNS INTEGER DECLARE Item : INTEGER IF TopOfStack = 0 THEN Item ← -1 ELSE Item ← UndoStack[TopOfStack] TopOfStack ← TopOfStack - 1 ENDIF RETURN ItemENDFUNCTION
    1 mark check for empty; 1 mark read item at top; 1 mark decrement after reading; 1 mark return item / −1.
Q13Stacks, queues & linked lists · Standard · Paper 2 style · 6 marks

A passport office in Islamabad gives each customer a token. Waiting tokens are held in a circular queue implemented with the array Queue[0:5] OF STRING.HeadPointer holds the index of the front item, TailPointer holds the index of the last item and NumberInQueue holds the number of items. Initially HeadPointer = 0, TailPointer = 5 and NumberInQueue = 0. On each enqueue, TailPointer is increased by 1 (wrapping from 5 to 0) and the token is stored there; on each dequeue the token at HeadPointer is removed and HeadPointer is increased by 1 (wrapping from 5 to 0).Operations in order: Enqueue T101, Enqueue T102, Enqueue T103, Enqueue T104, Enqueue T105, Dequeue, Dequeue, Enqueue T106, Enqueue T107, Dequeue

  1. (a) State the final values of HeadPointer, TailPointer and NumberInQueue. [3]
  2. (b) State the tokens still in the queue, from front to back. [1]
  3. (c) State the array index where T107 is stored and explain why. [2]
Show answer
  1. (a) HeadPointer = 3, TailPointer = 0, NumberInQueue = 4
    1 mark each.
  2. (b) T104, T105, T106, T107
    B1.
  3. (c) Index 0 — the queue is circular: after index 5 the tail pointer wraps round to index 0, which was freed by a dequeue.
    1 mark index; 1 mark wrap-round explanation.
Q14Stacks, queues & linked lists · Standard · Paper 2 style · 8 marks

A linked list of city names in alphabetical order is stored using two arrays, Data[0:7] and Pointer[0:7]. A pointer value of −1 means there is no next node. Unused nodes form a free list.Index | Data | Pointer0 | Multan | 41 | Gwadar | 32 | (empty) | 63 | Lahore | 04 | Quetta | −15 | Abbottabad | 16 | (empty) | 77 | (empty) | −1StartPointer = 5, FreeListPointer = 2

  1. (a) State the order in which the cities are output when the list is followed from StartPointer. [2]
  2. (b) Karachi is added to the list in alphabetical order, using the first node in the free list. State every value in the table (or pointer) that changes. [3]
  3. (c) Abbottabad is then deleted from the list and its node is added to the front of the free list. State the new values of StartPointer, FreeListPointer and Pointer[5]. [3]
Show answer
  1. (a) Abbottabad, Gwadar, Lahore, Multan, Quetta
    2 marks all in order; 1 mark first three correct.
  2. (b) Data[2] ← "Karachi"; Pointer[2] ← 3; Pointer[1] ← 2; FreeListPointer ← 6 (StartPointer unchanged at 5)
    1 mark Karachi stored in node 2 with Pointer[2] = 3; 1 mark Pointer[1] = 2; 1 mark FreeListPointer = 6.
  3. (c) StartPointer = 1, FreeListPointer = 5, Pointer[5] = 6
    1 mark each.
Q15Stacks, queues & linked lists · Challenge · Paper 2 style · 8 marks

A print server in a Karachi office holds print-job names in a circular queue using the global array Queue[0:9] OF STRING and the global integers HeadPointer, TailPointer and NumberInQueue.

  1. (a) Write pseudocode for the function Dequeue() RETURNS STRING, which removes and returns the item at the front of the queue. If the queue is empty it returns the string "EMPTY". [6]
  2. (b) Explain why a circular queue is used rather than a linear queue in an array. [2]
Show answer
  1. (a) FUNCTION Dequeue() RETURNS STRING DECLARE Item : STRING IF NumberInQueue = 0 THEN Item ← "EMPTY" ELSE Item ← Queue[HeadPointer] HeadPointer ← HeadPointer + 1 IF HeadPointer > 9 THEN HeadPointer ← 0 ENDIF NumberInQueue ← NumberInQueue - 1 ENDIF RETURN ItemENDFUNCTION
    1 mark each:• function header with RETURNS STRING• test for empty using NumberInQueue = 0 and "EMPTY" returned• item read from Queue[HeadPointer]• HeadPointer incremented• wrap round to 0 after 9 (accept HeadPointer ← (HeadPointer + 1) MOD 10)• NumberInQueue decremented and Item returned
  2. (b) In a linear queue, positions at the front become unusable after items are removed, so the queue can appear full while space is free; a circular queue reuses those positions by wrapping the pointers round.
    1 mark problem with linear queue; 1 mark reuse of freed space.
Q16Stacks, queues & linked lists · Challenge · Paper 2 style · 9 marks

A badminton club in Abbottabad stores its players' names in ranking order in a linked list. The global arrays are PlayerName[1:40] OF STRING and NextPointer[1:40] OF INTEGER. The global integer StartPointer holds the index of the first node; a pointer value of −1 marks the end of the list.

  1. (a) Write pseudocode for the function FindPosition(SearchName : STRING) RETURNS INTEGER. It follows the linked list from StartPointer and returns the position of SearchName in the list (1 for the first node, 2 for the second, …), or 0 if SearchName is not in the list. [7]
  2. (b) Explain why a linked list can be more efficient than a sorted array when a new name has to be inserted in order. [2]
Show answer
  1. (a) FUNCTION FindPosition(SearchName : STRING) RETURNS INTEGER DECLARE Current, Position, Result : INTEGER Current ← StartPointer Position ← 0 Result ← 0 WHILE Current <> -1 AND Result = 0 Position ← Position + 1 IF PlayerName[Current] = SearchName THEN Result ← Position ENDIF Current ← NextPointer[Current] ENDWHILE RETURN ResultENDFUNCTION
    1 mark each:• Current set to StartPointer• Position/Result initialised• loop until null pointer (−1)• loop also stops when found (or equivalent early exit)• Position incremented for each node visited• comparison of PlayerName[Current] with SearchName setting result• Current ← NextPointer[Current] and correct RETURN (0 if not found)
  2. (b) In an array, every item after the insertion point must be moved along one place; in a linked list the new item can go in any free node and only a couple of pointers need changing.
    1 mark array needs shifting; 1 mark linked list only updates pointers.
Q17Stacks, queues & linked lists · Challenge · Paper 4 style · 10 marks

A calculator app checks that brackets in a typed expression are balanced before evaluating it.

  1. (a) Write program code to:• declare a stack as an array of 20 elements and a top pointer (−1 when empty)• define push(item), which returns False if the stack is full, otherwise adds the item and returns True• define pop(), which returns an empty string if the stack is empty, otherwise removes and returns the top item• define balanced(expression), which uses the stack to return True if every bracket ( [ { in the expression is closed by the matching bracket in the correct order, and False otherwise• test balanced() with "(a+[b*c])", "{x-(y]}", "((2+3)" and ")(". [10]
Show answer
  1. (a) SIZE = 20stack = [""] * SIZEtop = -1def push(item): global top if top == SIZE - 1: return False top += 1 stack[top] = item return Truedef pop(): global top if top == -1: return "" item = stack[top] top -= 1 return itemdef balanced(expression): global top top = -1 # empty the stack pairs = {")": "(", "]": "[", "}": "{"} for ch in expression: if ch in "([{": if not push(ch): return False # too deeply nested elif ch in ")]}": if pop() != pairs[ch]: return False return top == -1tests = ["(a+[b*c])", "{x-(y]}", "((2+3)", ")(", "[(p+q)*{r-s}]", ""]for t in tests: print(repr(t), balanced(t))(Java or VB.NET solutions with the same logic are equally acceptable.)Test output:'(a+[b*c])' True'{x-(y]}' False'((2+3)' False')(' False'[(p+q)*{r-s}]' True'' True
    1 mark each, max 10:• array of 20 elements and top initialised to −1• push: full check (top = 19)• push: increments top then stores item, returns True• pop: empty check returning ""• pop: returns top item and decrements top• balanced: stack emptied at start• opening brackets pushed• closing bracket: pop and compare with matching opening bracket, returning False on mismatch / empty stack• returns True only if stack empty at end• tests called with all four strings and results output (evidence of running)
Q18Arrays · Core · Paper 2 style · 6 marks

A teacher in Quetta stores test marks in a 2D array.

  1. (a) Write a pseudocode statement to declare the 2D array Marks to hold one integer mark for each of 30 students in each of 5 subjects. [2]
  2. (b) Write a pseudocode statement to store a mark of 78 for student 12 in subject 3. [1]
  3. (c) Write pseudocode to set every element of Marks to −1. [3]
Show answer
  1. (a) DECLARE Marks : ARRAY[1:30, 1:5] OF INTEGER
    1 mark ARRAY[1:30, 1:5]; 1 mark OF INTEGER with DECLARE and identifier.
  2. (b) Marks[12, 3] ← 78
    B1.
  3. (c) FOR Student ← 1 TO 30 FOR Subject ← 1 TO 5 Marks[Student, Subject] ← -1 NEXT SubjectNEXT Student
    1 mark outer loop; 1 mark inner loop; 1 mark assignment using both indexes.
Q19Arrays · Core · Paper 2 style · 5 marks

A college in Bahawalpur stores 100 student IDs in the global array StudentID[1:100] OF STRING.

  1. (a) Write pseudocode for the function FindStudent(SearchID : STRING) RETURNS INTEGER, which performs a linear search of StudentID and returns the index of SearchID, or −1 if it is not found. The search should stop when the ID is found. [5]
Show answer
  1. (a) FUNCTION FindStudent(SearchID : STRING) RETURNS INTEGER DECLARE Index, Found : INTEGER Index ← 1 Found ← -1 WHILE Index <= 100 AND Found = -1 IF StudentID[Index] = SearchID THEN Found ← Index ENDIF Index ← Index + 1 ENDWHILE RETURN FoundENDFUNCTION
    1 mark each:• Index and result initialised• conditional loop up to 100• loop stops when found• comparison and index stored• correct RETURN (−1 if not found)
Q20Arrays · Standard · Paper 2 style · 6 marks

The array Temp[1:8] holds the daily maximum temperatures (°C) in Jacobabad for eight days: 41, 44, 43, 46, 48, 45, 47, 50 (Temp[1] = 41).Count ← 0Total ← 0FOR Day ← 2 TO 8 IF Temp[Day] > Temp[Day - 1] THEN Count ← Count + 1 Total ← Total + (Temp[Day] - Temp[Day - 1]) ENDIFNEXT DayOUTPUT Count, " ", Total

  1. (a) State the output of the algorithm. [2]
  2. (b) State what the value of Total represents. [1]
  3. (c) Write pseudocode to replace the IF statement so that the algorithm finds the largest single rise from one day to the next, stored in a variable BiggestRise (initialised to 0 before the loop). [3]
Show answer
  1. (a) 5 13
    Rises: 41→44 (3), 43→46 (3), 46→48 (2), 45→47 (2), 47→50 (3). B1 Count = 5; B1 Total = 13.
  2. (b) The sum of all the day-to-day temperature rises (falls are ignored).
    B1.
  3. (c) IF Temp[Day] - Temp[Day - 1] > BiggestRise THEN BiggestRise ← Temp[Day] - Temp[Day - 1]ENDIF
    1 mark difference calculated; 1 mark compared with BiggestRise; 1 mark BiggestRise updated. (For this data BiggestRise = 3.)
Q21Arrays · Standard · Paper 2 style · 6 marks

A bakery chain in Karachi records monthly sales (in rupees) in the global 2D array Sales[1:12, 1:4] OF REAL. Sales[m, b] holds the sales for month m at branch b.

  1. (a) Write pseudocode for the procedure BranchAverages(), which outputs the branch number and the average monthly sales for each of the four branches. [6]
Show answer
  1. (a) PROCEDURE BranchAverages() DECLARE Branch, Month : INTEGER DECLARE Total : REAL FOR Branch ← 1 TO 4 Total ← 0 FOR Month ← 1 TO 12 Total ← Total + Sales[Month, Branch] NEXT Month OUTPUT "Branch ", Branch, " average: ", Total / 12 NEXT BranchENDPROCEDURE
    1 mark each:• outer loop for 4 branches• Total reset to 0 inside the outer loop (before the inner loop)• inner loop for 12 months• correct indexing Sales[Month, Branch]• average calculated as Total / 12• output of branch number and average inside the outer loop, after the inner loop
Q22Arrays · Standard · Paper 4 style · 8 marks

Rainfall (mm) was recorded in three cities for seven days:Day | Lahore | Islamabad | Karachi1 | 12 | 0 | 52 | 30 | 8 | 03 | 0 | 0 | 24 | 45 | 22 | 105 | 6 | 3 | 06 | 0 | 15 | 187 | 9 | 4 | 7

  1. (a) Write program code to:• store the data in a 2D array (list of lists) with 7 rows (days) and 3 columns (cities)• define a function city_totals(data) that returns a list of the total rainfall for each city• define a function wettest_day(data) that returns the day number (1–7) with the greatest total rainfall across the three cities, and that total• output each city's name with its total, and the wettest day. [8]
Show answer
  1. (a) rainfall = [[12, 0, 5], [30, 8, 0], [0, 0, 2], [45, 22, 10], [6, 3, 0], [0, 15, 18], [9, 4, 7]]cities = ["Lahore", "Islamabad", "Karachi"]def city_totals(data): totals = [0, 0, 0] for day in range(7): for city in range(3): totals[city] += data[day][city] return totalsdef wettest_day(data): best_day = 0 best_total = sum(data[0]) for day in range(1, 7): day_total = 0 for city in range(3): day_total += data[day][city] if day_total > best_total: best_total = day_total best_day = day return best_day + 1, best_total # day number 1-7totals = city_totals(rainfall)for i in range(3): print(cities[i], totals[i], "mm")print("Wettest day:", wettest_day(rainfall))(Java or VB.NET solutions with the same logic are equally acceptable.)Test output:Lahore 102 mmIslamabad 52 mmKarachi 42 mmWettest day: (4, 77)
    1 mark each, max 8:• 2D array with 7 rows × 3 columns initialised with the data• city_totals: totals list initialised• nested loops over days and cities adding to the correct city total• list returned• wettest_day: loop over each day computing the day total• largest total and its day tracked correctly• day number returned as 1–7 (not index 0–6) with total• output of all three cities with totals and the wettest day
Q23Arrays · Challenge · Paper 2 style · 7 marks

A quiz app stores players' scores in ascending order in the global array Scores[1:100] OF INTEGER. The global integer NumScores holds how many elements are in use (they are Scores[1] to Scores[NumScores]).

  1. (a) Write pseudocode for the procedure InsertScore(NewScore : INTEGER).If the array is full the procedure outputs "Array full". Otherwise it inserts NewScore in the correct position, keeping the array in ascending order, and updates NumScores. You must not sort the whole array again. [7]
Show answer
  1. (a) PROCEDURE InsertScore(NewScore : INTEGER) DECLARE Index : INTEGER DECLARE Placed : BOOLEAN IF NumScores = 100 THEN OUTPUT "Array full" ELSE Index ← NumScores Placed ← FALSE WHILE Index >= 1 AND Placed = FALSE IF Scores[Index] > NewScore THEN Scores[Index + 1] ← Scores[Index] Index ← Index - 1 ELSE Placed ← TRUE ENDIF ENDWHILE Scores[Index + 1] ← NewScore NumScores ← NumScores + 1 ENDIFENDPROCEDURE
    1 mark each:• check for full array and output message• start at the last used element (NumScores)• loop that moves backwards while elements are larger• larger elements shifted one place right• loop stops at the start of the array without accessing Scores[0] (flag or equivalent)• NewScore stored at Index + 1• NumScores incrementedExample: Scores 12, 18, 25, 31 with NewScore 20 becomes 12, 18, 20, 25, 31.
Q24Arrays · Challenge · Paper 2 style · 7 marks

A cricket stadium in Lahore records seat bookings in the global 2D array Seats[1:20, 1:30] OF BOOLEAN. Seats[r, s] is TRUE if seat s in row r is free.

  1. (a) Write pseudocode for the function LongestRun(RowNum : INTEGER) RETURNS INTEGER, which returns the length of the longest group of consecutive free seats in the given row. [6]
  2. (b) Row 7 has seats 1 to 30 in this state (T = free, F = taken):FFTTTFTTTTFTTFFFTTTTTFFTTTFFTFState the value returned by LongestRun(7). [1]
Show answer
  1. (a) FUNCTION LongestRun(RowNum : INTEGER) RETURNS INTEGER DECLARE Seat, Current, Longest : INTEGER Current ← 0 Longest ← 0 FOR Seat ← 1 TO 30 IF Seats[RowNum, Seat] = TRUE THEN Current ← Current + 1 IF Current > Longest THEN Longest ← Current ENDIF ELSE Current ← 0 ENDIF NEXT Seat RETURN LongestENDFUNCTION
    1 mark each:• Current and Longest initialised to 0• loop through 30 seats of RowNum• Current incremented when seat free• Longest updated when Current exceeds it• Current reset to 0 when seat taken• Longest returned after loop
  2. (b) 5
    B1.
Q25Data types & records · Core · Paper 2 style · 6 marks

A library in Hyderabad stores details of each book.

  1. (a) Identify the most suitable data type for each field:(i) BookID, e.g. "HYD-00231"(ii) YearPublished, e.g. 2019(iii) Price, e.g. 1250.50(iv) OnLoan, whether the book is currently borrowed(v) ReturnDate, the date the book is due back [5]
  2. (b) A book ID such as 00231 contains only digits. Explain why it should still be stored as a STRING. [1]
Show answer
  1. (a) (i) STRING (ii) INTEGER (iii) REAL (iv) BOOLEAN (v) DATE
    1 mark each.
  2. (b) It is not used in calculations, and storing it as a number would lose the leading zeros.
    B1 either point.
Q26Data types & records · Core · Paper 2 style · 3 marks
  1. (a) Explain what is meant by a record data type. [2]
  2. (b) Give one advantage of storing student details in an array of records rather than in several separate 1D arrays. [1]
Show answer
  1. (a) A user-defined (composite) data type that groups together several related data items (fields), which can be of different data types, under one identifier.
    1 mark composite / user-defined; 1 mark fields of different types.
  2. (b) All the data about one student is kept together in one element, so it is easier to manage / sort / pass to a module without the arrays getting out of step.
    B1.
Q27Data types & records · Standard · Paper 2 style · 6 marks

A clinic in Peshawar is writing a program to store patient details.

  1. (a) Write pseudocode to define the record type Patient with the fields PatientID (e.g. "PSH4471"), FullName, DateOfBirth, WeightKg (e.g. 68.5) and Insured (yes/no). [4]
  2. (b) Write a pseudocode statement to declare an array Patients that can hold 200 Patient records. [1]
  3. (c) Write a pseudocode statement to set the weight of the 15th patient to 68.5 kg. [1]
Show answer
  1. (a) TYPE Patient DECLARE PatientID : STRING DECLARE FullName : STRING DECLARE DateOfBirth : DATE DECLARE WeightKg : REAL DECLARE Insured : BOOLEANENDTYPE
    1 mark TYPE Patient … ENDTYPE; 1 mark PatientID and FullName STRING; 1 mark DateOfBirth DATE; 1 mark WeightKg REAL and Insured BOOLEAN.
  2. (b) DECLARE Patients : ARRAY[1:200] OF Patient
    B1.
  3. (c) Patients[15].WeightKg ← 68.5
    B1.
Q28Data types & records · Standard · Paper 2 style · 6 marks
  1. (a) Evaluate each expression and state the data type of the result.(i) 47 MOD 6(ii) 47 DIV 6(iii) LENGTH("Hyderabad")(iv) MID("Rawalpindi", 3, 4)(v) STR_TO_NUM(RIGHT("PK-2026", 4)) + 1(vi) INT(17 / 4) [6]
Show answer
  1. (a) (i) 5, INTEGER(ii) 7, INTEGER(iii) 9, INTEGER(iv) "walp", STRING(v) 2027, INTEGER (accept REAL)(vi) 4, INTEGER
    1 mark each for the correct value and data type. MID("Rawalpindi", 3, 4) starts at the 3rd character and takes 4 characters; 17 / 4 = 4.25 and INT keeps the whole-number part. (v) RIGHT gives "2026"; STR_TO_NUM converts it to a number, so INTEGER (or REAL) is accepted.
Q29Data types & records · Challenge · Paper 2 style · 7 marks

An online shop in Lahore stores product details in the global array Products[1:500] OF Product, where Product is this record type:TYPE Product DECLARE Code : STRING DECLARE Category : STRING DECLARE Price : REAL DECLARE InStock : INTEGERENDTYPE

  1. (a) Write pseudocode for the function AveragePrice(Cat : STRING) RETURNS REAL, which returns the average price of all products in the category Cat. Unused array elements have Code set to "" and must be ignored. The function returns −1 if there are no products in that category. [7]
Show answer
  1. (a) FUNCTION AveragePrice(Cat : STRING) RETURNS REAL DECLARE Index, Count : INTEGER DECLARE Total : REAL Count ← 0 Total ← 0.0 FOR Index ← 1 TO 500 IF Products[Index].Code <> "" AND Products[Index].Category = Cat THEN Total ← Total + Products[Index].Price Count ← Count + 1 ENDIF NEXT Index IF Count = 0 THEN RETURN -1.0 ELSE RETURN Total / Count ENDIFENDFUNCTION
    1 mark each:• Count and Total initialised• loop through all 500 elements• unused elements skipped (Code <> "")• category compared using record field notation Products[Index].Category• Total and Count updated• check for Count = 0 returning −1• Total / Count returned
Q30Data types & records · Challenge · Paper 2 style · 7 marks

A coaching centre in Islamabad uses these variables:Age ← 17Name ← "Mehwish"Paid ← FALSEFee ← 2500.0

  1. (a) Evaluate each expression and state the data type of the result.(i) (Age >= 16) AND NOT Paid(ii) LENGTH(Name) > 6 OR Fee < 2000(iii) Fee * 0.8(iv) TO_UPPER(LEFT(Name, 3)) & NUM_TO_STR(Age)(v) (Age MOD 4 = 1) AND (Fee > 3000) [5]
  2. (b) Write a pseudocode expression that is TRUE only when the fee has not been paid and Name starts with the letter M. [2]
Show answer
  1. (a) (i) TRUE, BOOLEAN(ii) TRUE, BOOLEAN(iii) 2000.0, REAL(iv) "MEH17", STRING(v) FALSE, BOOLEAN
    1 mark each for correct value and type. (ii) LENGTH("Mehwish") = 7 > 6 so TRUE even though Fee < 2000 is FALSE. (v) 17 MOD 4 = 1 is TRUE but Fee > 3000 is FALSE.
  2. (b) (Paid = FALSE) AND (LEFT(Name, 1) = "M")
    1 mark NOT Paid / Paid = FALSE; 1 mark LEFT(Name, 1) = "M" (or MID(Name, 1, 1) = "M") joined with AND.

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).

Text files Banker9 questions · 8/9 sessions
Stacks, queues & linked lists 7 questions · 6/9 sessions
Arrays 9 questions · 6/9 sessions
Data types & records Banker12 questions · 8/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
Text files Banker658/9
Stacks, queues & linked lists 576/9
Arrays 436/9
Data types & records Banker368/9

← All Computer Science topics