Volume II· mock paper · walk-in sheet

CMS 710 · The Test Questions, Answered in Full

Four questions set by the lecturer are on file and every one comes from Module 4. This volume answers all four at full exam length, then drills the comparisons that the rest of the course is built from.
Prepared by Mbosinwa Awunor · www.mbosinwa.dev
Exam: Wednesday 12 Aug 2026 Time: 11:00 – 14:00 Venue: the exam hall Lecturers: the lecturers

The four-part answer shape · use it on every question

Every question this examiner has set is a pair of concepts to compare, and three of the four say "with an example". So every answer gets the same four moves, in this order:
  1. Define both terms · one sentence each, in the module's own words
  2. A comparison table with a basis of comparison column and six or more rows
  3. A code example showing the difference actually happening, with its output
  4. One closing sentence on why the difference matters to a language designer
Move 2 carries the most marks per minute. Move 4 is what separates a good answer from a full one · and almost nobody writes it.

1Question 1 · Control flow defined; sequence vs iteration

(i) Control flow, defined

Control flow refers to the order in which statements, instructions or function calls are executed in a program. It is governed by control structures · the mechanisms that determine the sequence of execution.

Control flow determines four things:

  1. Which instruction executes next
  2. Under what conditions execution changes direction
  3. How repetition occurs
  4. How data moves through program components

It is commonly represented using flowcharts, control-flow graphs or execution traces.

Why it matters: without control structures, programs would execute instructions strictly in the order they appear, making it impossible to implement decision-making, loops or complex algorithms. The design of control structures significantly influences program readability, software reliability, maintainability and execution efficiency.

The four forms of control flow are sequential execution, selection, iteration and recursion.

Add this and the definition part is complete: the three principles of control structures · program behaviour is determined by control structures; simplicity improves readability; abstraction reduces complexity (foreach loops, iterators, generators, recursive functions).

(ii) Sequence vs iteration

Sequential execution is the simplest form of control flow: statements are executed one after another in the order they appear. Iteration allows a set of instructions to execute repeatedly until a specified condition is satisfied; it is commonly called looping.

BasisSequenceIteration
DefinitionStatements executed once each, in written orderA block executed repeatedly until a condition is met
RepetitionNone · each statement runs exactly onceYes · the same block runs many times
ConditionNo condition involvedControlled by a condition that is tested each pass
Direction of flowStrictly forward, top to bottomReturns to the start of the block
ConstructsOrdinary statementsfor · while · do-while
Code length vs workOne statement does one unit of workOne statement does many units of work
TerminationAlways terminatesMay not terminate if the condition never becomes false
PurposePerform steps in a fixed orderAvoid duplicating code; reduce redundancy
SEQUENCE                ITERATION
x = 10                  for i in range(5):
y = 20                      print(i)
z = x + y
print(z)

Execution order:        Output:  0 1 2 3 4
  1. x = 10             One statement, five
  2. y = 20             executions · the flow
  3. z = x + y          returns to the top of
  4. print(z)           the block each pass.
Four statements,
each run once.

Closing sentence: sequential execution alone cannot support decision-making or repetition, which is precisely why languages provide selection and iteration · iteration reduces code duplication, improves efficiency and simplifies repetitive tasks.

2Question 2 · What is recursion, and how does it differ from iteration?

Definition

Recursion is a control mechanism in which a function calls itself to solve a problem. It applies to problems that can be broken into smaller sub-problems of the same kind.

A recursive solution has two essential parts:

Without a base case the recursion never stops, the call stack grows without bound, and the program fails with a stack overflow.

The example · factorial

n! = n × (n − 1)!
RECURSIVE                ITERATIVE
def factorial(n):        def factorial(n):
    if n == 1:               result = 1
        return 1             for i in range(1, n+1):
    return n * \                 result *= i
        factorial(n-1)       return result
TRACE of factorial(5) · recursive
factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1              ← BASE CASE reached

unwinding:  2*1=2  3*2=6  4*6=24  5*24 = 120

Draw that two-column trace · the winding down to the base case and the unwinding back up. It shows the marker you understand why recursion uses more memory: five calls are alive at once, each holding its own n.

Recursion vs iteration · the comparison table

BasisRecursionIteration
MechanismA function calls itself on a smaller sub-problemA loop repeats a block of code
TerminationA base caseA loop condition that eventually becomes false
Memory useHigher · every call adds a stack frameLower · one set of variables reused
SpeedOften slower · function-call overheadFaster · no call overhead
Code sizeShorter, closer to the mathematical definitionLonger but more explicit
ReadabilityElegant for hierarchical problems, harder for beginners to traceStraightforward to follow step by step
Failure modeStack overflow if the base case is missing or never reachedInfinite loop if the condition never fails
Best suited toTrees, graphs, divide-and-conquer, hierarchical structuresSimple counted or condition-controlled repetition
StateHeld implicitly on the call stackHeld explicitly in loop variables

Advantages and disadvantages, as the module lists them

Advantages of recursionDisadvantages
Elegant solutionsHigher memory consumption
Natural representation of hierarchical structuresRisk of stack overflow
Useful for trees and graphsOften slower than iteration
The closing sentence. Recursion and iteration are computationally equivalent · anything one can do, the other can too. The choice is therefore not about power but about clarity versus cost: recursion buys a solution that mirrors the structure of the problem, and pays for it in stack memory and call overhead. Which is why a language designer offering excellent recursion support, as Python, JavaScript and C++ all do, must also give programmers loops.

3Question 3 · Global vs local scope, and variable lifetime

Definitions first

Scope determines where a variable can be accessed within a program. It is a fundamental concept because it controls variable visibility and lifetime.

Global scope · the variable is accessible throughout the program, from any function or block.
Local scope · the variable is accessible only within the function or block in which it is declared.

The module names a third: block scope, where variables exist only inside a specific block · in JavaScript, let age = 20; declared inside an if block produces an error if read outside it.

BasisGlobal scopeLocal scope
Where declaredOutside all functions and blocksInside a function or block
VisibilityEverywhere in the programOnly within its own function or block
Created whenThe program startsThe function is called
Destroyed whenThe program endsThe function returns
LifetimeEntire program executionOnly while the function executes
Memory areaStatic / global storageThe call stack
Name conflictsRisk of clashes across the programSame name may be reused safely in different functions
Effect on modularityWeakens it · any function may change the valueSupports it · data stays where it is used

The example

x = 10                  # GLOBAL · visible everywhere

def test():
    y = 20              # LOCAL · visible only in test()
    print(x)            # legal: globals are visible here
    print(y)            # legal

test()
print(x)                # legal · 10
print(y)                # ERROR: y does not exist here

Using scope to explain lifetime · what the question actually wants

Variable lifetime is the period during which a variable exists in memory. It depends on scope, the storage allocation method and the program execution state.

The link, stated directly. Scope and lifetime are two views of the same declaration. Scope is a spatial property · where in the program text the name is visible. Lifetime is a temporal property · for how long during execution the storage exists. They are connected because the scope in which a variable is declared determines the storage it is given, and that storage determines how long it lives:
  • A variable declared in global scope is allocated in static storage when the program loads, so its lifetime is the entire execution.
  • A variable declared in local scope is allocated on the call stack when its function is entered and reclaimed when the function returns, so its lifetime is just that one call.
THE LIFETIME OF EACH VARIABLE, ON A TIMELINE

program starts ─────────────────────────────► ends
      │                                          │
  x created                                 x destroyed   ← GLOBAL
      │                                          │
      │    test() called ──────► returns         │
      │          │                    │          │
      │      y created           y destroyed     │        ← LOCAL
      │
  Each further call to test() creates a NEW y and
  destroys it again · the value is not carried over.

The consequence worth stating: because a local variable is destroyed on return, it cannot remember anything between calls; because a global survives, any function can change it, which is why globals are convenient but harmful to modularity.

Importance of scope · the four points

  1. Prevents naming conflicts · two functions may each use i without interference
  2. Enhances security · data is not exposed beyond where it is needed
  3. Improves maintainability · a change to a local variable cannot affect distant code
  4. Supports modular design · modules communicate through parameters, not shared state

4Question 4 · Pass by value vs pass by reference

Definitions

Functions often require data from other parts of a program, and languages provide parameter-passing mechanisms for supplying it.

Pass-by-value: a copy of the argument is passed to the function. Changes made inside the function do not affect the original variable.

Pass-by-reference: the function receives a reference to the original variable. Changes made inside the function affect the original.

BasisPass by valuePass by reference
What is passedA copy of the valueA reference to the original variable
C++ syntaxvoid f(int x)void f(int &x)
Effect on originalUnchangedModified
MemoryExtra memory for the copyNo copy · more memory-efficient for large data
SpeedSlower for large objects (copying cost)Faster · nothing is duplicated
SafetySafer · the caller's data cannot be corruptedRiskier · unintended changes are possible
Side effectsNoneYes · this is its purpose
Use whenThe function only needs to read the valueThe function must modify the caller's variable, or the data is large

The example, with output

PASS BY VALUE
#include <iostream>
using namespace std;

void increment(int x) {      // a COPY
    x++;
    cout << "inside:  " << x << endl;
}

int main() {
    int num = 10;
    increment(num);
    cout << "outside: " << num << endl;
    return 0;
}

OUTPUT   inside:  11
         outside: 10      ← original UNCHANGED
PASS BY REFERENCE
#include <iostream>
using namespace std;

void increment(int &x) {     // the ACTUAL variable
    x++;
    cout << "inside:  " << x << endl;
}

int main() {
    int num = 10;
    increment(num);
    cout << "outside: " << num << endl;
    return 0;
}

OUTPUT   inside:  11
         outside: 11      ← original MODIFIED

The two programs differ by a single character · the & · and that is exactly what makes them worth putting side by side in an answer.

Python's mechanism · the extra mark

Python uses an approach usually described as pass-by-object-reference: objects are passed by reference to object values.

def modify(lst):
    lst.append(100)         # the ORIGINAL list is modified

numbers = [1, 2, 3]
modify(numbers)
print(numbers)              # [1, 2, 3, 100]

def reassign(lst):
    lst = [9, 9, 9]         # rebinds the local name only

reassign(numbers)
print(numbers)              # [1, 2, 3, 100] · unchanged

The subtlety worth one sentence: in Python, mutating an object through the parameter affects the caller, but rebinding the parameter to a new object does not · which is why it is neither pure pass-by-value nor pure pass-by-reference.

The closing sentence. The choice of parameter-passing mechanism is a language design decision balancing safety against efficiency and expressive power: pass-by-value protects the caller's data but copies it, pass-by-reference avoids the copy and permits a function to return results through its parameters, at the cost of side effects that make programs harder to reason about. This is why the module rates parameter-passing complexity as low in Python, moderate in JavaScript and high in C++ · C++ gives the programmer every option and the responsibility that comes with it.

5The other comparisons this course is built from

Every question set so far has been a comparison. These are the remaining pairs the four modules set up · learn the basis words in the left column and the tables write themselves.

Syntax vs semantics

ConcernStructure · how it is writtenMeaning · what it does
Checked byThe parserSemantic analysis / runtime
Example error= x 10Dividing by a variable that is zero

Static vs dynamic typing

CheckedAt compile timeAt run time
LanguagesC++Python, JavaScript
GainsEarly errors, reliability, speedFlexibility, faster development
CostsVerbosity, less flexibilityRuntime errors, less type safety

Strong vs weak typing

ConversionsPreventedAllowed implicitly
ExamplePython age + "years" → errorJS "5" + 2"52"

Primitive vs composite vs user-defined types

PrimitiveProvided by the language, cannot be decomposed · int, float, char, bool
CompositeCombine primitives into one structure · arrays, lists, tuples, dictionaries, objects
User-definedCreated by the programmer · structs, classes, enumerations, records

Array vs list

SizeFixedDynamic · grows and shrinks
MemoryContiguousExtra overhead
AccessFast, by indexSlower for some operations
Insert/deleteCostlyFlexible

Stack vs queue

RuleLIFOFIFO
OperationsPush · Pop · Peek · IsEmptyEnqueue · Dequeue · Front · IsEmpty
UsesBrowser history, undo, function calls, expression evaluationBank queues, print queues, OS scheduling, network packets

Parse tree vs abstract syntax tree

RepresentsThe full grammatical structure per the grammarA simplified structure preserving meaning
Produced bySyntax analysis (parsing)Semantic analysis
DetailKeeps every grammar symbolRemoves unnecessary grammar details
Used byThe parserCompilers, interpreters, static analysis, optimizers, AI code assistants

Imperative vs functional control flow

DescribesHow a task is performedWhat is to be computed
Exampletotal = 0; for n in numbers: total += ntotal = sum(numbers)
GainsExplicit controlSimpler code, abstraction, fewer side effects

Compiled vs interpreted

TranslationWhole program before executionStatement by statement during execution
SpeedFaster at run timeSlower
ErrorsFound before runningFound when the line is reached
ExampleC++Python · JavaScript (JIT)

ADT vs data structure

SpecifiesWhat · the data and permitted operationsHow · the actual organization in memory
ExampleStack ADT: Push, Pop, Peek, IsEmptyThat stack built on an array or a linked list

6Mock paper · sit this closed-book

RIVERS STATE UNIVERSITY · PGD COMPUTER SCIENCE · CMS 710 · PRINCIPLES OF PROGRAMMING LANGUAGES
Mock examination · Time allowed: 3 hours · Answer any FIVE questions · Each question carries 20 marks · Illustrate your answers with examples in Python, JavaScript or C++

QQuestionMarks
1(a) Define a programming language and state the three perspectives from which it may be viewed. (b) Differentiate between syntax and semantics with examples. (c) State and explain the five goals of programming language design.5 + 6 + 9
2(a) Trace the evolution of programming languages through the four generations, giving an example and two characteristics of each. (b) What is a language specification and what does it define? (c) Write the BNF rule for an assignment statement and explain its meaning.10 + 5 + 5
3(a) Define a data type and state the four things it specifies. (b) Differentiate between primitive, composite and user-defined data types with examples in three languages. (c) Compare static and dynamic typing, and separately strong and weak typing, in tables.5 + 7 + 8
4(a) What is data abstraction? Illustrate with an analogy and state four benefits. (b) Define an Abstract Data Type and illustrate with the Stack ADT. (c) Differentiate an ADT from a data structure.7 + 8 + 5
5(a) Differentiate between a stack and a queue, giving operations and two real-life uses of each. (b) With diagrams, distinguish a parse tree from an abstract syntax tree. (c) Explain the role of trees in the four phases of language processing.7 + 7 + 6
6(a) Define control flow and state what it determines. (b) Differentiate between sequence and iteration with examples. (c) What is recursion, and how does it differ from iteration? Use factorial to illustrate.5 + 7 + 8
7(a) Differentiate between global and local scope, and use that distinction to explain variable lifetime. (b) Compare pass by value and pass by reference with a C++ example of each. (c) Explain Python's pass-by-object-reference.8 + 8 + 4

Where each answer lives: Q1, Q2 → Vol I §2 · Q3 → Vol I §3 · Q4 → Vol I §3–§4 · Q5 → Vol I §4 · Q6, Q7 → this volume §1–§4 · those two are the real test questions, reassembled.

7Rapid-fire recall · cover the right column

PromptAnswer
Programming language, in one lineA formal language of symbols, keywords, syntax rules and semantic rules used to instruct a computer
Three perspectives on a languageCommunication · problem-solving · formal system
The four generations1GL machine · 2GL assembly · 3GL high-level · 4GL logic/AI
Five design goalsReadability · writability · reliability · maintainability · efficiency
Syntax vs semanticsStructure vs meaning
What a specification definesSyntax, semantics, data types, operators, control structures, libraries, runtime behaviour
BNF assignment rule<assignment> ::= <identifier> = <expression>
Three principles of language definitionFormal rules govern every language · simplicity vs expressiveness · efficiency vs safety
A data type specifies…Values · operations · memory required · interpretation
Three type categoriesPrimitive · composite · user-defined
Static vs dynamic typingChecked at compile time vs at run time
Strong vs weak typingPrevents vs allows implicit conversions
Where Python sits on both axesDynamic and strong
Data abstractionHiding implementation, exposing essentials · the car analogy
Four benefits of abstractionSimplicity · reusability · maintainability · security
PromptAnswer
Data structure, in one lineA method of organizing and storing data so it can be accessed and modified efficiently
ADT, in one lineA logical description of data and operations without implementation details
Four ADT advantagesAbstraction · reusability · maintainability · modularity
Stack ADT operationsPush · Pop · Peek · IsEmpty
Queue ADT operationsEnqueue · Dequeue · Front · IsEmpty
Three data-structure principlesEfficient organization · abstraction of complexity · time–space trade-off
Parse tree vs ASTFull grammatical structure vs simplified, meaning-preserving
The four language-processing phasesLexical analysis → tokens · parsing → parse trees · semantic analysis → ASTs · code generation
Control flow, in one lineThe order in which statements, instructions or function calls are executed
Four forms of control flowSequential · selection · iteration · recursion
Three types of selectionSingle · double · multiple
The three loopsfor known count · while condition · do-while at least once
Two parts of a recursive solutionBase case · recursive case
Three types of scopeGlobal · local · block
Variable lifetime depends on…Scope · storage allocation method · program execution state
Three parameter-passing mechanismsBy value · by reference · Python's by object reference
The IPO modelInput → Processing → Output
Structured programming emphasizes…Sequence, selection, iteration · avoiding uncontrolled GOTO

8Walk-in sheet · the last ten minutes

The four test questions, in one line each

  1. Control flow = the order in which statements, instructions or function calls are executed. Sequence runs each statement once in order; iteration runs a block repeatedly under a condition.
  2. Recursion = a function calling itself, with a base case and a recursive case. Versus iteration: more memory (stack frames), slower, shorter code, risks stack overflow · best for trees and hierarchies.
  3. Global = visible everywhere, lives for the whole program; local = visible in one function, lives only while it runs. Scope is spatial, lifetime is temporal, and scope determines lifetime.
  4. By value = a copy, original unchanged; by reference (&) = the actual variable, original modified. Python is pass-by-object-reference.

The four-move answer shape

Define both → table with a basis column → code example with output → one sentence on why it matters to a language designer.

The three tables to have ready

  • Python / JavaScript / C++: block structure = indentation / braces / braces · typing = dynamic / dynamic / static · compilation = interpreted / JIT / compiled · readability = very high / high / moderate · speed = moderate / moderate / high
  • Type axes: Python dynamic+strong · JavaScript dynamic+weak · C++ static+strong
  • Structures: stack LIFO, queue FIFO, array fixed, list dynamic

Three moves in the first five minutes

  1. Read all the questions and pick the five with the most comparisons · those are the fastest to answer well.
  2. For each chosen question, sketch the table headings in the margin before writing prose.
  3. Name all three languages wherever a comparison is invited; the whole course is built on that trio.

If your mind goes blank

Write the definition of each term, then draw a two-column table and fill the basis column with: definition · mechanism · memory · speed · safety · use when. Those six words fit almost every pair on this syllabus.