2.2.1 Programming Techniques
2.2.1(a) Programming Constructs
The Three Basic Constructs
| Construct | Purpose | Typical syntax |
|---|---|---|
| Sequence | Execute statements in fixed order | Straight line code |
| Branching (selection) | Choose path based on condition | IF / ELSEIF / CASE |
| Iteration | Repeat a block multiple times | FOR / WHILE / REPEAT UNTIL |
| Construct | Example behaviour |
|---|---|
| Sequence | Read name/age, then print messages in order |
| Branching | IF age-based message OR CASE day-name mapping |
| Iteration | FOR counter loop, WHILE password check, REPEAT-UNTIL guessing loop |
// Sequence
name = input("Enter name: ")
age = input("Enter age: ")
print("Hello " + name)
print("You are " + age + " years old")
// Branching
if age >= 18 then
print("You can vote")
elseif age >= 16 then
print("You can drive")
else
print("You are too young")
end if
switch day:
case 1: print("Monday")
case 2: print("Tuesday")
case 3: print("Wednesday")
default: print("Other day")
end switch
// Iteration
for i = 1 to 10:
print(i)
end for
while password != "secret" do
password = input("Enter password: ")
end while
repeat
guess = input("Guess the number: ")
until guess == targetNumber
2.2.1(b) Recursion
Advantages and Disadvantages
| Advantages | Disadvantages |
|---|---|
| Simplifies code for naturally recursive problems (factorials, Fibonacci) | Memory-intensive (each call adds a frame to the call stack) |
| Often results in more elegant, readable solutions | Risk of stack overflow with deep recursion |
| Fewer lines of code compared to iterative solutions | Debugging can be challenging |
| Direct translation of mathematical definitions | May be slower than iteration due to function call overhead |
function factorial(n):
if n == 0 OR n == 1 then
return 1
end if
return n * factorial(n - 1)
end function
| Call | Expansion |
|---|---|
| factorial(4) | 4 × factorial(3) |
| factorial(3) | 3 × factorial(2) |
| factorial(2) | 2 × factorial(1) |
| factorial(1) | 1 (base case) |
// Recursive Fibonacci
function fibRecursive(n):
if n <= 1 then
return n
end if
return fibRecursive(n-1) + fibRecursive(n-2)
end function
// Iterative Fibonacci
function fibIterative(n):
if n <= 1 then
return n
end if
a = 0
b = 1
for i = 2 to n:
temp = a + b
a = b
b = temp
end for
return b
end function
2.2.1(c) Global and Local Variables
Local Variables
| Scope type | Where accessible | Strengths | Risks |
|---|---|---|---|
| Local variable | Only inside defining block/subroutine | Encapsulation, safer changes, better memory lifecycle | Not directly shareable outside scope |
| Global variable | Across whole program | Convenient shared state | Hidden dependencies, accidental overwrite, harder debugging |
// Global variable
global MAX_SIZE = 100
procedure example():
// Local variable
local count = 0
count = count + 1
print(count) // Works: prints 1
print(MAX_SIZE) // Works: accesses global
end procedure
// Main program
example()
print(MAX_SIZE) // Works: prints 100
print(count) // ERROR! count is local to example()
Best Practice: Minimise global variables. Pass data via parameters instead.
2.2.1(d) Modularity, Functions, and Procedures
Top-Down Design
• Start with highest-level problem
• Break down into smaller sub-problems
• Each sub-problem handled by a module
• Makes complex problems manageable
• Allows team collaboration
Functions vs Procedures
| Routine type | Return behaviour | Typical use |
|---|---|---|
| Function | Returns a value | Calculations / expressions (e.g. average = calcMean(scores)) |
| Procedure | Usually no direct return value | Performing actions/side effects (e.g. print, write, update) |
// PASS BY VALUE: subroutine gets a copy
procedure doubleByValue(x):
x = x * 2
print(x) // Prints 20
end procedure
number = 10
doubleByValue(number)
print(number) // Still 10! Original unchanged
// PASS BY REFERENCE: subroutine can modify original
procedure doubleByReference(ref x):
x = x * 2
print(x) // Prints 20
end procedure
number = 10
doubleByReference(number)
print(number) // Now 20! Original was modified
When to use pass by reference:
• Need to return multiple values
• Modifying large data structures (avoid copying)
• When the subroutine must change the original
2.2.1(e) Use of an Integrated Development Environment (IDE)
Key IDE Features
| IDE feature | What it helps with |
|---|---|
| Stepping | Run line-by-line to trace logic |
| Variable watch | Observe changing values in real time |
| Breakpoints | Pause execution at key points |
| Source editor tools | Faster coding with highlight/autocomplete/bracket matching |
| Debug tooling | Locate runtime errors and inspect state |
| Integrated tooling | Refactoring, compiler/interpreter, version control, project management |
| Line | Code | Variables/state |
|---|---|---|
| 1 | total = 0 | total = 0 |
| 2 | count = 0 | total = 0, count = 0 |
| 4 | total = total + score | breakpoint: inspect values each loop |
| 7 | average = total / count | risk: division by zero if count == 0 |
1. Set breakpoint at line 4
2. Run program and inspect variables each iteration
3. Detect count == 0 path
4. Fix with guard condition before division
2.2.1(f) Use of Object-Oriented Techniques
Classes and Objects
| OOP term | Meaning |
|---|---|
| Class | Blueprint defining attributes and methods |
| Object | Instance created from a class |
| Instantiation | Process of creating an object |
Encapsulation
class BankAccount:
// Private attributes (encapsulated)
private accountNumber
private balance
private ownerName
// Public methods (controlled access)
public procedure new(number, name):
accountNumber = number
ownerName = name
balance = 0
end procedure
public procedure deposit(amount):
if amount > 0 then
balance = balance + amount
end if
end procedure
public function getBalance():
return balance
end function
end class
// Usage
myAccount = new BankAccount("12345", "Alice")
myAccount.deposit(100)
print(myAccount.getBalance()) // 100
// myAccount.balance = 1000000 // ERROR! Private attribute
Encapsulation benefits:
• Data protection from invalid modifications
• Controlled access through methods
• Implementation details hidden
• Easier to maintain and modify
• Know the three basic constructs (sequence, selection, iteration)
• Understand recursion: base case, recursive case, stack behavior
• Be able to compare recursion vs iteration
• Know scope: local vs global variables and their trade-offs
• Understand parameter passing: by value vs by reference
• Know IDE features: stepping, breakpoints, variable watch
• Understand OOP basics: classes, objects, encapsulation
• Be able to trace recursive algorithms