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.

New to a topic? Read the Data Structures & Algorithms notes first, then come back to practise.

01

Data Structures

Multiple choice · 6

Q1Why can an array reach element 500 instantly while a linked list cannot?

  1. AArrays are stored in faster memory
  2. BArray elements are contiguous, so the address can be computed arithmetically
  3. CLinked lists are always longer
  4. 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?

  1. AArray
  2. BLinked list
  3. CBinary search tree
  4. 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?

  1. ACustomers waiting at a bank counter
  2. BUndo history in a text editor
  3. CPrint jobs on a shared printer
  4. 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?

  1. ARandom order
  2. BAscending sorted order
  3. CLevel by level
  4. 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?

  1. AThe tree runs out of memory
  2. BThe tree degenerates into a linked list and search becomes O(n)
  3. CThe values get stored in the wrong order
  4. 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?

  1. AA stack
  2. BA queue
  3. CA hash table
  4. 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.
  1. Explain why a queue is the appropriate structure for this task. [2]
  2. Describe how a circular queue avoids the problem of a linear queue in a fixed-size array. [3]
  3. State what must be checked before a job is added. [1]
Mark scheme
  1. Jobs must be printed in the order they were submitted[1]
  2. A queue removes items in the same order they were added, which is first-in-first-out[1]
  3. In a linear queue the front pointer moves forward and the space behind it is wasted[1]
  4. A circular queue wraps the rear pointer round to the start of the array[1]
  5. So the freed space is reused and the array does not appear full while space remains[1]
  6. 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.
  1. Draw the resulting tree. [3]
  2. Write down the in-order traversal. [2]
  3. State what the in-order traversal of any binary search tree always produces, and give one use of that property. [2]
Mark scheme
  1. 50 at the root with 30 on its left and 70 on its right[1]
  2. 20 and 40 as the children of 30[1]
  3. 60 as the left child of 70[1]
  4. Visits left subtree, then node, then right subtree[1]
  5. 20, 30, 40, 50, 60, 70[1]
  6. The values in ascending order[1]
  7. 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.
  1. Describe the steps needed to insert Chand in the correct position. [3]
  2. Explain why no data has to be moved, unlike in an array. [2]
Mark scheme
  1. Traverse from the head until the node after which Chand belongs is found, here Bilal[1]
  2. Create the new node and set its pointer to whatever Bilal was pointing at, that is Danish[1]
  3. Set Bilal's pointer to the new nodethis order matters or the rest of the list is lost[1]
  4. The nodes are not stored in consecutive memory locations[1]
  5. 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?

  1. AO(5n + 300)
  2. BO(n)
  3. CO(300)
  4. 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?

  1. A1,000,000
  2. B1,000
  3. C20
  4. 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?

  1. ASelection sort
  2. BInsertion sort
  3. CBubble sort with no early exit
  4. 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²)?

  1. AWhen the array contains duplicates
  2. BWhen the pivot repeatedly splits the array very unevenly
  3. CWhen n is a prime number
  4. 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?

  1. AIt uses too much memory
  2. BEvery extra input element doubles the total work
  3. CIt only works on sorted data
  4. 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?

  1. ABig-O is wrong here
  2. BNothing — Big-O describes growth rate, not absolute speed
  3. CThey must have different complexities
  4. 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.
  1. Write out the list after each complete pass. [3]
  2. State the total number of passes needed and explain how the algorithm knows it has finished. [2]
  3. State the time complexity of a bubble sort and explain why it is unsuitable for large data sets. [2]
Mark scheme
  1. After pass 1: 3, 5, 1, 8[1]
  2. After pass 2: 3, 1, 5, 8[1]
  3. After pass 3: 1, 3, 5, 8[1]
  4. Three passes; a fourth confirms no swaps[1]
  5. A flag records whether any swap was made; if a whole pass makes none, the list is sorted[1]
  6. O(n²)[1]
  7. 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.
  1. Write pseudocode for a binary search on this list. [5]
  2. Explain what your code returns when the name is not present. [1]
  3. Compare the number of comparisons with a linear search on the same list. [2]
Mark scheme
  1. Initialises low = 1 and high = 5000[1]
  2. Loops while low <= high[1]
  3. Calculates mid = (low + high) DIV 2[1]
  4. Compares and returns mid if the name matches[1]
  5. Otherwise sets high = mid − 1 or low = mid + 1 correctly[1]
  6. Returns a value such as −1 or FALSE once low > high[1]
  7. Binary search: at most 13 comparisons, since 2¹³ = 8192[1]
  8. 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).
  1. Name one sorting algorithm with this complexity. [1]
  2. Explain why it scales better than O(n²) as n grows. [2]
  3. 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
  1. Merge sort or quicksort (average case)[1]
  2. The log n factor grows very slowly compared with the extra factor of n[1]
  3. So the gap between the two widens rapidly as n increases[1]
  4. Doubling n slightly more than doubles n log n[1]
  5. 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:

  1. Aa loop
  2. Ba base case
  3. Can array
  4. 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:

  1. Areturn zero
  2. Bcause a stack overflow
  3. Crun faster
  4. 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:

  1. Aonly the return value
  2. Bthe return address, parameters and local variables
  3. Cthe whole program
  4. 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?

  1. A1
  2. B3
  3. C4
  4. 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:

  1. Aon the way down
  2. Bon the way back up after the base case
  3. Call at once at the start
  4. 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?

  1. Afirst in, first out
  2. Blast in, first out
  3. Crandom order
  4. 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:

  1. Ait cannot solve the same problems
  2. Bit uses more memory for stack frames
  3. Cit is harder to write
  4. 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:

  1. Asumming a list of numbers
  2. Btraversing a tree
  3. Ccounting to ten
  4. 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
  1. (a) Base case: S(1) = 1. Recursive case: S(n) = n + S(n−1).Both must be identified separately.[1]
  2. (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]
  3. S(1) returns 1 — the base case.This starts the unwinding.[1]
  4. 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]
  5. (c) Advantage: the code closely matches the mathematical definition, so it is shorter and clearer.Readability is the usual advantage.[1]
  6. 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:

  1. Arandom order
  2. Bascending sorted order
  3. Clevel order
  4. 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:

  1. Afaster
  2. BO(log n) still
  3. CO(n) — it becomes a chain
  4. 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:

  1. Astoring data twice
  2. Bperforming rotations to keep the height ~log n
  3. Csorting on every read
  4. 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:

  1. Athe whole tree is sorted
  2. Bthe smallest value is at the root
  3. Csearch is O(log n)
  4. 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:

  1. Astack
  2. Bplain array
  3. Cpriority queue (heap)
  4. 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:

  1. Ai−1 and i+1
  2. B2i+1 and 2i+2
  3. Ci/2 and i/3
  4. 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:

  1. Akeeps everything sorted
  2. Bcomputes the slot from the key instead of searching
  3. Cuses a balanced tree
  4. 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?

  1. Ait must be reversible
  2. Bit must be deterministic and spread keys evenly
  3. Cit must be secret
  4. 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:

  1. Arehash
  2. Bcollision
  3. Cload factor
  4. 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:

  1. Aonly the last key
  2. Ba small list of all of them
  3. Cnothing — it errors
  4. 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:

  1. Agets faster
  2. Bsuffers more collisions and may resize
  3. Cbecomes sorted
  4. 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:

  1. Athe array is empty
  2. Bmany keys collide into one slot
  3. Ckeys are integers
  4. 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:

  1. Aa graph with no cycles
  2. Ba graph with n² edges
  3. Can array of nodes
  4. 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:

  1. Aadjacency matrix
  2. Badjacency list
  3. Ca 2D array of size n²
  4. 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:

  1. Athe deepest node
  2. Bthe fewest-edges path on an unweighted graph
  3. Ca minimum spanning tree
  4. 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:

  1. Aadding weights
  2. Breplacing the queue with a stack
  3. Csorting the nodes
  4. 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:

  1. Aa topological order
  2. Bshortest paths with non-negative weights
  3. Call cycles
  4. 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:

  1. Aany graph
  2. Ba directed acyclic graph (DAG)
  3. Conly trees
  4. 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:

  1. Ausing more processors
  2. Bsolving each subproblem once and storing the result
  3. Csorting the input first
  4. 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:

  1. Aa sorted array
  2. Boptimal substructure
  3. Ca hash function
  4. 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:

  1. Abottom-up table filling
  2. Btop-down recursion with a cache
  3. Csorting then searching
  4. 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:

  1. Agives different answers
  2. Bbuilds up from base cases without recursion
  3. Cnever stores results
  4. 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:

  1. AO(n)
  2. BO(log n)
  3. CO(2ⁿ)
  4. 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?

  1. Abinary search
  2. Bthe 0/1 knapsack
  3. Cbubble sort
  4. 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?

  1. AThey are the same thing
  2. BA class is a blueprint; an object is one instance built from it
  3. CA class holds data; an object holds methods
  4. 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?

  1. APrivate fields use less memory
  2. BIt lets the class validate every change and protect its own invariants
  3. CIt makes the program run faster
  4. 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:

  1. AEncapsulation
  2. BPolymorphism
  3. CAbstraction
  4. 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?

  1. AA Dog is an Animal
  2. BA Car has an Engine
  3. CA Square is a Shape
  4. 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?

  1. ACode runs faster
  2. BCallers depend on what a class does, not how, so internals can change safely
  3. CIt reduces the number of classes
  4. 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:

  1. AOverloading
  2. BOverriding
  3. CEncapsulating
  4. 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.
  1. Explain what inheritance is and state one advantage of using it here. [3]
  2. Suggest two attributes that belong in Person and one that belongs only in Student. [3]
  3. Explain how polymorphism could be used when printing a list of all people. [2]
Mark scheme
  1. A subclass automatically acquires the attributes and methods of its parent class[1]
  2. Student and Teacher both get name and address without redefining them[1]
  3. Advantage: the shared code is written once, so a change is made in one place[1]
  4. In Person: name[1]
  5. In Person: date of birth or address[1]
  6. In Student only: class or roll number[1]
  7. Each subclass overrides a describe method with its own version[1]
  8. 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.
  1. Explain why balance is private rather than public. [2]
  2. Describe the validation the withdraw method should perform. [2]
  3. Write pseudocode for the withdraw method. [3]
Mark scheme
  1. Other code cannot change it directly[1]
  2. So every change passes through a method that can validate it, keeping the balance consistent[1]
  3. The amount must be positive[1]
  4. The amount must not exceed the current balance[1]
  5. Method header taking an amount parameter[1]
  6. IF amount > 0 AND amount <= balance THEN subtract and return TRUE[1]
  7. ELSE return FALSE without changing the balance[1]
Q6[5 marks]
A programmer writes Shape s = new Circle(5) where Circle inherits from Shape.
  1. Explain why this statement is allowed. [2]
  2. The Shape class has an abstract method area. Explain what abstract means here and what Circle must do. [3]
Mark scheme
  1. A Circle is a Shape, so an object of the subclass can be held in a variable of the parent type[1]
  2. This lets one variable or array hold objects of several related classes[1]
  3. An abstract method is declared but has no implementation in the base class[1]
  4. No object of the abstract class itself can be created[1]
  5. Circle must provide its own area method, returning π × radius²[1]

These questions come from the Data Structures & Algorithms lessons — each topic has its own notes, worked examples and an interactive diagram.