Data Structures & Algorithms — MCQs & Practice Questions
50 multiple-choice questions and 23 exam-style questions with mark schemes, organised by chapter, with answers you can check as you go. Free, no sign-up.
Q1Why can an array reach element 500 instantly while a linked list cannot?
AArrays are stored in faster memory
BArray elements are contiguous, so the address can be computed arithmetically
CLinked lists are always longer
DArrays keep a separate index table
Show answer
Correct answer: B — Array elements are contiguous, so the address can be computed arithmetically
Contiguity is the whole trick: address = base + 500 × elementSize, one multiply and one add. A linked list scatters its nodes, so the only way to find node 500 is to follow 500 pointers from the head.
Q2You need to add and remove items constantly at the front of a collection. Which structure fits best?
AArray
BLinked list
CBinary search tree
DHash table
Show answer
Correct answer: B — Linked list
Front insertion and deletion on a linked list is O(1) — you only re-point the head. An array would shift every remaining element on each operation, making it O(n) every single time.
Q3A stack is LIFO. Which real situation matches it?
ACustomers waiting at a bank counter
BUndo history in a text editor
CPrint jobs on a shared printer
DCars passing through a tunnel
Show answer
Correct answer: B — Undo history in a text editor
Undo reverses your most recent action first — last in, first out. The other three are FIFO: the first to arrive is the first served, which is a queue.
Q4An in-order traversal of a binary search tree outputs the values in what order?
ARandom order
BAscending sorted order
CLevel by level
DReverse insertion order
Show answer
Correct answer: B — Ascending sorted order
In-order visits left subtree, then node, then right subtree. Because a BST puts every smaller value left and every larger value right, that recursion emits values from smallest to largest. It is effectively a free sort.
Q5Inserting already-sorted data into a plain binary search tree causes what problem?
AThe tree runs out of memory
BThe tree degenerates into a linked list and search becomes O(n)
CThe values get stored in the wrong order
DNothing — the tree self-balances
Show answer
Correct answer: B — The tree degenerates into a linked list and search becomes O(n)
Each new value is larger than everything before it, so it always goes right. The result is a single chain with no branching, and lookup degrades from O(log n) to O(n). Self-balancing trees exist precisely to prevent this.
Q6Breadth-first search needs which helper structure?
AA stack
BA queue
CA hash table
DAn array of size n²
Show answer
Correct answer: B — A queue
BFS explores level by level, so nodes must come out in the same order they were discovered — FIFO, a queue. Swapping in a stack turns the same algorithm into depth-first search.
Exam-style questions · 6
Q1[2 marks]
State one advantage and one disadvantage of an array compared with a linked list.
Answer
Advantage: any element can be reached directly from its index in constant time. Disadvantage: inserting at the front requires every later element to be shifted.
Q2[2 marks]
Explain the difference between a stack and a queue.
Answer
A stack is last-in-first-out: items are added and removed at the same end. A queue is first-in-first-out: items are added at one end and removed from the other.
Q3[3 marks]
A stack is implemented with an array and a pointer. Describe what happens to the pointer during a push and during a pop.
Answer
On a push the pointer is incremented and the new item is written at that position. On a pop the item at the pointer is read and the pointer is decremented. The pointer must be checked against the array bounds first.
Q4[6 marks]
A program uses a queue to hold print jobs waiting for a printer.
Explain why a queue is the appropriate structure for this task. [2]
Describe how a circular queue avoids the problem of a linear queue in a fixed-size array. [3]
State what must be checked before a job is added. [1]
Mark scheme
Jobs must be printed in the order they were submitted[1]
A queue removes items in the same order they were added, which is first-in-first-out[1]
In a linear queue the front pointer moves forward and the space behind it is wasted[1]
A circular queue wraps the rear pointer round to the start of the array[1]
So the freed space is reused and the array does not appear full while space remains[1]
That the queue is not full[1]
Q5[7 marks]
A binary search tree is built by inserting the values 50, 30, 70, 20, 40, 60 in that order.
Draw the resulting tree. [3]
Write down the in-order traversal. [2]
State what the in-order traversal of any binary search tree always produces, and give one use of that property. [2]
Mark scheme
50 at the root with 30 on its left and 70 on its right[1]
20 and 40 as the children of 30[1]
60 as the left child of 70[1]
Visits left subtree, then node, then right subtree[1]
20, 30, 40, 50, 60, 70[1]
The values in ascending order[1]
It can therefore be used to sort the data, or to output it in order without re-sorting[1]
(b) 20, 30, 40, 50, 60, 70
Q6[5 marks]
A linked list stores the names Ali, Bilal, Danish in alphabetical order. Each node holds a name and a pointer.
Describe the steps needed to insert Chand in the correct position. [3]
Explain why no data has to be moved, unlike in an array. [2]
Mark scheme
Traverse from the head until the node after which Chand belongs is found, here Bilal[1]
Create the new node and set its pointer to whatever Bilal was pointing at, that is Danish[1]
Set Bilal's pointer to the new nodethis order matters or the rest of the list is lost[1]
The nodes are not stored in consecutive memory locations[1]
Order is held by the pointers, so changing two pointers is enough[1]
02
Algorithms and Complexity
Multiple choice · 6
Q1An algorithm takes 5n + 300 steps. What is its complexity?
AO(5n + 300)
BO(n)
CO(300)
DO(n²)
Show answer
Correct answer: B — O(n)
Big-O keeps only the fastest-growing term and drops constant factors. As n grows large, 5n dominates the fixed 300, and the 5 does not change the shape of the curve. What is left is O(n).
Q2Binary search on a sorted array of 1,000,000 items takes roughly how many comparisons?
A1,000,000
B1,000
C20
D2
Show answer
Correct answer: C — 20
Each comparison halves the search space, so the count is log₂(1,000,000) ≈ 20. That is the practical power of logarithmic growth: a thousand-fold more data costs only about ten extra steps.
Q3Which sort is fastest on data that is already almost sorted?
ASelection sort
BInsertion sort
CBubble sort with no early exit
DAll are identical
Show answer
Correct answer: B — Insertion sort
Insertion sort only shifts elements that are genuinely out of place. On nearly-sorted input almost nothing moves, so it approaches O(n). Selection sort scans the entire remaining array every pass regardless, so it stays O(n²) no matter how ordered the data is.
Q4Quicksort is O(n log n) on average. When does it degrade to O(n²)?
AWhen the array contains duplicates
BWhen the pivot repeatedly splits the array very unevenly
CWhen n is a prime number
DIt never degrades
Show answer
Correct answer: B — When the pivot repeatedly splits the array very unevenly
Quicksort relies on the pivot cutting the array roughly in half. If the pivot is always the smallest or largest element — as happens when you take the last element of an already-sorted array — each partition removes just one item, giving n levels of recursion instead of log n.
Q5Why does O(2ⁿ) become unusable so quickly?
AIt uses too much memory
BEvery extra input element doubles the total work
CIt only works on sorted data
DIt requires recursion
Show answer
Correct answer: B — Every extra input element doubles the total work
Doubling per element is brutal. Going from n = 50 to n = 51 does not add a step, it adds as much work as all 50 previous elements combined. Exponential algorithms are typically replaced with dynamic programming or approximation.
Q6Two algorithms are O(n). One runs in 2 seconds, the other in 10. What does Big-O say about this?
ABig-O is wrong here
BNothing — Big-O describes growth rate, not absolute speed
CThey must have different complexities
DThe 10-second one is really O(n²)
Show answer
Correct answer: B — Nothing — Big-O describes growth rate, not absolute speed
Big-O deliberately ignores constant factors. Both will scale the same way — double the input and both roughly double their time — even though one is five times slower throughout. For choosing between two same-class algorithms you need real measurement, not Big-O.
Exam-style questions · 6
Q1[2 marks]
State one condition that must be met before a binary search can be used, and state why.
Answer
The data must already be sorted. The algorithm discards half the list at each step by comparing with the middle item, which is only valid if the order is known.
Q2[2 marks]
Explain what is meant by the time complexity of an algorithm.
Answer
A measure of how the number of operations grows as the size of the input grows, written in big-O notation. It describes the trend, not the exact running time on a particular machine.
Q3[3 marks]
A linear search of 1000 items takes at most 1000 comparisons. State the maximum number a binary search would need, and explain.
Answer
About 10, because 2¹⁰ = 1024. Each comparison halves the remaining list, so the maximum is log₂ n rounded up.
Q4[7 marks]
A bubble sort is used on the list 5, 3, 8, 1.
Write out the list after each complete pass. [3]
State the total number of passes needed and explain how the algorithm knows it has finished. [2]
State the time complexity of a bubble sort and explain why it is unsuitable for large data sets. [2]
Mark scheme
After pass 1: 3, 5, 1, 8[1]
After pass 2: 3, 1, 5, 8[1]
After pass 3: 1, 3, 5, 8[1]
Three passes; a fourth confirms no swaps[1]
A flag records whether any swap was made; if a whole pass makes none, the list is sorted[1]
O(n²)[1]
Doubling the data quadruples the work, so it becomes impractically slow[1]
Q5[8 marks]
A program must find whether a student name appears in a sorted list of 5000 names.
Write pseudocode for a binary search on this list. [5]
Explain what your code returns when the name is not present. [1]
Compare the number of comparisons with a linear search on the same list. [2]
Mark scheme
Initialises low = 1 and high = 5000[1]
Loops while low <= high[1]
Calculates mid = (low + high) DIV 2[1]
Compares and returns mid if the name matches[1]
Otherwise sets high = mid − 1 or low = mid + 1 correctly[1]
Returns a value such as −1 or FALSE once low > high[1]
Binary search: at most 13 comparisons, since 2¹³ = 8192[1]
Linear search: up to 5000, so binary search is dramatically faster[1]
Q6[5 marks]
An algorithm is described as having complexity O(n log n).
Name one sorting algorithm with this complexity. [1]
Explain why it scales better than O(n²) as n grows. [2]
A data set of 1000 items takes 2 seconds with the O(n log n) algorithm. Estimate the time for 2000 items and justify your estimate. [2]
Mark scheme
Merge sort or quicksort (average case)[1]
The log n factor grows very slowly compared with the extra factor of n[1]
So the gap between the two widens rapidly as n increases[1]
Doubling n slightly more than doubles n log n[1]
So roughly 4.2 to 4.5 seconds, a little over doubleaccept "just over 4 seconds" with reasoning[1]
03
Recursion
Multiple choice · 8
Q1A recursive routine must always contain:
Aa loop
Ba base case
Can array
Da global variable
Show answer
Correct answer: B — a base case
The base case is what allows the recursion to stop. Without it the calls never end.
Q2A recursive function with no base case will:
Areturn zero
Bcause a stack overflow
Crun faster
Dskip the recursion
Show answer
Correct answer: B — cause a stack overflow
Every call pushes a frame and none ever returns, so the stack memory is exhausted.
Q3A stack frame stores:
Aonly the return value
Bthe return address, parameters and local variables
Cthe whole program
Dnothing
Show answer
Correct answer: B — the return address, parameters and local variables
It holds everything needed to resume the suspended call once the deeper one returns.
Q4For F(n) = n × F(n−1) with F(1) = 1, calling F(4) pushes how many frames?
A1
B3
C4
D24
Show answer
Correct answer: C — 4
Frames are pushed for F(4), F(3), F(2) and F(1) — four in total. 24 is the result, not the depth.
Q5During recursion, calculations happen:
Aon the way down
Bon the way back up after the base case
Call at once at the start
Dnot at all
Show answer
Correct answer: B — on the way back up after the base case
Each call is suspended at the recursive call. The work is completed as the frames are popped.
Q6Recursive calls complete in which order?
Afirst in, first out
Blast in, first out
Crandom order
Dall simultaneously
Show answer
Correct answer: B — last in, first out
The stack is LIFO, so the most recently pushed frame is the first to be popped and completed.
Q7The main disadvantage of recursion compared with iteration is:
Ait cannot solve the same problems
Bit uses more memory for stack frames
Cit is harder to write
Dit always gives wrong answers
Show answer
Correct answer: B — it uses more memory for stack frames
Anything recursive can be written iteratively; the cost is one stack frame per level of depth.
Q8Recursion is most naturally suited to:
Asumming a list of numbers
Btraversing a tree
Ccounting to ten
Dreading one input
Show answer
Correct answer: B — traversing a tree
A tree is itself defined recursively, so a recursive traversal matches the structure. Simple repetition is better served by a loop.
Exam-style questions · 5
Q1[2 marks]
State the two conditions a recursive routine must satisfy in order to terminate.
Answer
It must have a base case that returns a value without calling itself, and each recursive call must make progress towards that base case — typically by reducing the parameter.
Q2[3 marks]
Explain the role of the stack when a recursive routine executes.
Answer
Each call pushes a stack frame containing the return address, the parameters and any local variables, so the suspended call can be resumed. Frames accumulate as the recursion descends. When the base case returns, the frames are popped in reverse order — last in, first out — with each completing its calculation as it goes.
Q3[2 marks]
A recursive function is written with no base case. Describe what happens when it runs.
Answer
It calls itself indefinitely, pushing a new stack frame each time and never returning. The stack eventually runs out of memory and the program terminates with a stack overflow error.
Q4[6 marks]
A function is defined as: S(1) = 1, and S(n) = n + S(n−1) for n > 1. (a) State the base case and the recursive case. (b) Trace S(5), showing the calls and the returns. (c) Give one advantage and one disadvantage of using recursion here rather than a loop.
Mark scheme
(a) Base case: S(1) = 1. Recursive case: S(n) = n + S(n−1).Both must be identified separately.[1]
(b) S(5) calls S(4), which calls S(3), S(2) and finally S(1). Five frames are pushed.The descent, with nothing computed yet.[1]
S(1) returns 1 — the base case.This starts the unwinding.[1]
S(2) = 2 + 1 = 3; S(3) = 3 + 3 = 6; S(4) = 4 + 6 = 10; S(5) = 5 + 10 = 15.Returns in reverse order of the calls.[1]
(c) Advantage: the code closely matches the mathematical definition, so it is shorter and clearer.Readability is the usual advantage.[1]
Disadvantage: each call uses a stack frame, so it needs more memory and risks stack overflow for large n.Memory cost is the standard disadvantage.[1]
(a) S(1)=1 and S(n)=n+S(n−1); (b) S(5) = 15; (c) clarity vs stack memory
Q5[2 marks]
Give one situation where recursion is clearly preferable to iteration, and one where iteration is preferable.
Answer
Recursion is preferable for recursive data structures such as traversing a tree, or for divide-and-conquer algorithms like quicksort, where an iterative version would need an explicit stack of its own. Iteration is preferable for simple repetition such as summing a list, where recursion would waste memory on stack frames for no gain in clarity.
04
Trees, Heaps & Priority Queues
Multiple choice · 6
Q1An in-order traversal of a binary search tree outputs values in:
Arandom order
Bascending sorted order
Clevel order
Dreverse insertion order
Show answer
Correct answer: B — ascending sorted order
In-order visits left, node, right; with the BST invariant that emits values smallest to largest.
Q2Inserting already-sorted data into a plain BST makes search:
Afaster
BO(log n) still
CO(n) — it becomes a chain
Dimpossible
Show answer
Correct answer: C — O(n) — it becomes a chain
Each value goes the same direction, so the tree degenerates into a linked list with O(n) search.
Q3Self-balancing trees maintain performance by:
Astoring data twice
Bperforming rotations to keep the height ~log n
Csorting on every read
Dusing a hash function
Show answer
Correct answer: B — performing rotations to keep the height ~log n
AVL and red-black trees rotate after insertions/deletions so the height stays logarithmic.
Q4A min-heap guarantees that:
Athe whole tree is sorted
Bthe smallest value is at the root
Csearch is O(log n)
Dit has no duplicates
Show answer
Correct answer: B — the smallest value is at the root
The heap property only fixes the root as the minimum; the rest is not fully ordered.
Q5The best data structure for "always remove the most urgent item next" is a:
Astack
Bplain array
Cpriority queue (heap)
Dhash table
Show answer
Correct answer: C — priority queue (heap)
A heap-backed priority queue peeks the extreme in O(1) and removes it in O(log n).
Q6In an array-based heap, the children of index i are at:
Ai−1 and i+1
B2i+1 and 2i+2
Ci/2 and i/3
Dthe ends of the array
Show answer
Correct answer: B — 2i+1 and 2i+2
The complete-tree layout puts the children of i at 2i+1 and 2i+2, so no pointers are needed.
05
Hashing & Hash Tables
Multiple choice · 6
Q1A hash table looks items up in O(1) on average because it:
Akeeps everything sorted
Bcomputes the slot from the key instead of searching
Cuses a balanced tree
Dchecks every element
Show answer
Correct answer: B — computes the slot from the key instead of searching
The hash function turns the key straight into an index, so the table jumps to the slot.
Q2Which is a required property of a hash function used for a hash table?
Ait must be reversible
Bit must be deterministic and spread keys evenly
Cit must be secret
Dit must sort the keys
Show answer
Correct answer: B — it must be deterministic and spread keys evenly
Same key → same index (deterministic), and an even spread to minimise collisions.
Q3Two different keys hashing to the same slot is called a:
Arehash
Bcollision
Cload factor
Dprobe
Show answer
Correct answer: B — collision
That is the definition of a collision — unavoidable, so tables plan for it.
Q4In chaining, a slot that receives several colliding keys holds:
Aonly the last key
Ba small list of all of them
Cnothing — it errors
Da copy of the whole table
Show answer
Correct answer: B — a small list of all of them
Chaining stores colliding keys in a list at that slot; look-up walks just that list.
Q5As the load factor rises, a hash table:
Agets faster
Bsuffers more collisions and may resize
Cbecomes sorted
Dloses data
Show answer
Correct answer: B — suffers more collisions and may resize
More items per slot means more collisions, so the table rehashes into a bigger array to stay O(1).
Q6Hash-table look-up degrades toward O(n) when:
Athe array is empty
Bmany keys collide into one slot
Ckeys are integers
Dthe load factor is very low
Show answer
Correct answer: B — many keys collide into one slot
A crowded slot has a long list to walk, pushing that look-up toward linear time.
06
Graphs & Graph Algorithms
Multiple choice · 6
Q1A tree is best described as:
Aa graph with no cycles
Ba graph with n² edges
Can array of nodes
Da weighted matrix
Show answer
Correct answer: A — a graph with no cycles
A tree is a connected graph with no cycles; graphs are the more general structure.
Q2For a sparse graph (few edges), the more space-efficient representation is:
Aadjacency matrix
Badjacency list
Ca 2D array of size n²
Da hash of all pairs
Show answer
Correct answer: B — adjacency list
An adjacency list uses O(n+e) space; a matrix always uses O(n²) regardless of how few edges exist.
Q3Breadth-first search uses a queue and is used to find:
Athe deepest node
Bthe fewest-edges path on an unweighted graph
Ca minimum spanning tree
Dthe largest cycle
Show answer
Correct answer: B — the fewest-edges path on an unweighted graph
BFS explores level by level, so it reaches each node by a shortest hop-count path.
Q4Turning BFS into DFS requires only:
Aadding weights
Breplacing the queue with a stack
Csorting the nodes
Da hash table
Show answer
Correct answer: B — replacing the queue with a stack
BFS with a queue explores broad; swap in a stack (LIFO) and the same algorithm explores deep — that is DFS.
Q5Dijkstra's algorithm finds:
Aa topological order
Bshortest paths with non-negative weights
Call cycles
Dthe adjacency matrix
Show answer
Correct answer: B — shortest paths with non-negative weights
Dijkstra finalises the nearest unvisited node repeatedly, computing shortest paths when weights are non-negative.
Q6A topological sort can be produced for:
Aany graph
Ba directed acyclic graph (DAG)
Conly trees
Donly weighted graphs
Show answer
Correct answer: B — a directed acyclic graph (DAG)
Topological ordering requires a DAG — no cycles, and directed so edges can all point forward.
07
Dynamic Programming
Multiple choice · 6
Q1Dynamic programming speeds up recursion by:
Ausing more processors
Bsolving each subproblem once and storing the result
Csorting the input first
Dremoving the base case
Show answer
Correct answer: B — solving each subproblem once and storing the result
DP caches subproblem answers so repeated subproblems are never recomputed.
Q2DP requires overlapping subproblems and:
Aa sorted array
Boptimal substructure
Ca hash function
Dno recursion at all
Show answer
Correct answer: B — optimal substructure
The optimal solution must be buildable from the optimal solutions of its subproblems.
Q3Memoization is best described as:
Abottom-up table filling
Btop-down recursion with a cache
Csorting then searching
Diterating with two pointers
Show answer
Correct answer: B — top-down recursion with a cache
Memoization keeps the recursion and caches each result — top-down.
Q4Tabulation differs from memoization in that it:
Agives different answers
Bbuilds up from base cases without recursion
Cnever stores results
Donly works on graphs
Show answer
Correct answer: B — builds up from base cases without recursion
Tabulation fills a table bottom-up from the base cases; both compute each subproblem once.
Q5Naive recursive Fibonacci runs in roughly:
AO(n)
BO(log n)
CO(2ⁿ)
DO(1)
Show answer
Correct answer: C — O(2ⁿ)
Its calls branch exponentially because subproblems are recomputed, giving about O(2ⁿ).
Q6Which is a classic dynamic-programming problem?
Abinary search
Bthe 0/1 knapsack
Cbubble sort
Dhashing a key
Show answer
Correct answer: B — the 0/1 knapsack
The knapsack (best value under a weight limit) is a textbook DP problem, along with coin change and LCS.
08
Object-Oriented Design
Multiple choice · 6
Q1What is the difference between a class and an object?
AThey are the same thing
BA class is a blueprint; an object is one instance built from it
CA class holds data; an object holds methods
DAn object can only exist once per program
Show answer
Correct answer: B — A class is a blueprint; an object is one instance built from it
The class defines the structure and behaviour once. Each object created from it gets its own copy of the data. One Student class can produce a thousand student objects, each with different names and marks.
Q2Why make a field private and expose it through methods?
APrivate fields use less memory
BIt lets the class validate every change and protect its own invariants
CIt makes the program run faster
DThe compiler requires it
Show answer
Correct answer: B — It lets the class validate every change and protect its own invariants
That is encapsulation. If balance can only change through withdraw(), you have exactly one place to enforce "never go below zero". A public field can be corrupted from anywhere, and finding the culprit later is painful.
Q3Circle and Rectangle both extend Shape and both define area(). This is:
AEncapsulation
BPolymorphism
CAbstraction
DComposition
Show answer
Correct answer: B — Polymorphism
Polymorphism means "many forms": one method name resolving to different implementations depending on the actual object type. It is what lets a single loop over a mixed list of shapes call area() on each without checking what type it is.
Q4Which relationship is better modelled by composition than inheritance?
AA Dog is an Animal
BA Car has an Engine
CA Square is a Shape
DA Manager is an Employee
Show answer
Correct answer: B — A Car has an Engine
A car is not a kind of engine — it contains one. Inheritance expresses "is a", composition expresses "has a". Using inheritance for a has-a relationship produces classes that inherit members that make no sense for them.
Q5What is the main benefit of abstraction?
ACode runs faster
BCallers depend on what a class does, not how, so internals can change safely
CIt reduces the number of classes
DIt removes the need for testing
Show answer
Correct answer: B — Callers depend on what a class does, not how, so internals can change safely
Abstraction draws a line between interface and implementation. As long as the public methods keep their promises, you can rewrite the internals completely and every caller keeps working — which is what makes large codebases maintainable.
Q6A subclass provides its own version of a method that already exists in its parent. This is called:
AOverloading
BOverriding
CEncapsulating
DInstantiating
Show answer
Correct answer: B — Overriding
Overriding replaces the inherited behaviour with the subclass's own, using the same name and signature. Overloading is different: it means several methods sharing a name but taking different parameter lists, resolved at compile time.
Exam-style questions · 6
Q1[2 marks]
Explain the difference between a class and an object.
Answer
A class is the template that defines the attributes and methods. An object is a particular instance of that class, created at run time, with its own values for those attributes.
Q2[2 marks]
State what is meant by encapsulation and give one benefit.
Answer
Attributes are made private and are accessed only through public methods. This prevents other code from setting an attribute to an invalid value.
Q3[3 marks]
Explain the difference between overriding and overloading a method.
Answer
Overriding replaces an inherited method in a subclass with a new version having the same signature. Overloading defines several methods with the same name but different parameter lists in the same class.
Q4[8 marks]
A school system has a base class Person and subclasses Student and Teacher.
Explain what inheritance is and state one advantage of using it here. [3]
Suggest two attributes that belong in Person and one that belongs only in Student. [3]
Explain how polymorphism could be used when printing a list of all people. [2]
Mark scheme
A subclass automatically acquires the attributes and methods of its parent class[1]
Student and Teacher both get name and address without redefining them[1]
Advantage: the shared code is written once, so a change is made in one place[1]
In Person: name[1]
In Person: date of birth or address[1]
In Student only: class or roll number[1]
Each subclass overrides a describe method with its own version[1]
The program calls describe on every item in the list and the correct version runs automatically[1]
Q5[7 marks]
A class BankAccount has a private attribute balance and public methods deposit and withdraw.
Explain why balance is private rather than public. [2]
Describe the validation the withdraw method should perform. [2]
Write pseudocode for the withdraw method. [3]
Mark scheme
Other code cannot change it directly[1]
So every change passes through a method that can validate it, keeping the balance consistent[1]
The amount must be positive[1]
The amount must not exceed the current balance[1]
Method header taking an amount parameter[1]
IF amount > 0 AND amount <= balance THEN subtract and return TRUE[1]
ELSE return FALSE without changing the balance[1]
Q6[5 marks]
A programmer writes Shape s = new Circle(5) where Circle inherits from Shape.
Explain why this statement is allowed. [2]
The Shape class has an abstract method area. Explain what abstract means here and what Circle must do. [3]
Mark scheme
A Circle is a Shape, so an object of the subclass can be held in a variable of the parent type[1]
This lets one variable or array hold objects of several related classes[1]
An abstract method is declared but has no implementation in the base class[1]
No object of the abstract class itself can be created[1]
Circle must provide its own area method, returning π × radius²[1]