H446/02 · Algorithms & ProgrammingSection 2.2

2.2.1 Programming techniques

Variables, constants, operators, inputs, outputs, sequence, selection, iteration, subroutines, recursion, global and local variables, modularity and parameters

📚2.2.1 Programming Techniques

2.2.1(a) Programming Constructs

Definition
Programming constructs are the building blocks used to control the flow of a program. In structured programming, three main constructs are employed: sequence, branching (selection), and iteration.

The Three Basic Constructs

Key Point
ConstructPurposeTypical syntax
SequenceExecute statements in fixed orderStraight line code
Branching (selection)Choose path based on conditionIF / ELSEIF / CASE
IterationRepeat a block multiple timesFOR / WHILE / REPEAT UNTIL

Worked Example
Programming Constructs Examples

ConstructExample behaviour
SequenceRead name/age, then print messages in order
BranchingIF age-based message OR CASE day-name mapping
IterationFOR counter loop, WHILE password check, REPEAT-UNTIL guessing loop

text
// 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

Definition
Recursion is a programming technique where a function calls itself in order to solve a problem. This continues until a base condition is met, at which point the recursion halts and the stack unwinds.

Advantages and Disadvantages

Pros & Cons
Pros & Cons (Recursion):

AdvantagesDisadvantages
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 solutionsRisk of stack overflow with deep recursion
Fewer lines of code compared to iterative solutionsDebugging can be challenging
Direct translation of mathematical definitionsMay be slower than iteration due to function call overhead

Worked Example
Recursion Example: Factorial

text
function factorial(n):
    if n == 0 OR n == 1 then
        return 1
    end if
    return n * factorial(n - 1)
end function

Key Point
CallExpansion
factorial(4)4 × factorial(3)
factorial(3)3 × factorial(2)
factorial(2)2 × factorial(1)
factorial(1)1 (base case)
Unwinding result: 2 × 1 = 2, 3 × 2 = 6, 4 × 6 = 24

text
// 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

Definition
Variable scope determines where a variable can be accessed within a program. Local variables are restricted to their block/subroutine, while global variables are accessible throughout the entire program.

Local Variables

Key Point
Scope typeWhere accessibleStrengthsRisks
Local variableOnly inside defining block/subroutineEncapsulation, safer changes, better memory lifecycleNot directly shareable outside scope
Global variableAcross whole programConvenient shared stateHidden dependencies, accidental overwrite, harder debugging

Worked Example
Scope Example

text
// 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

Definition
Modular programming is the practice of breaking down a large program into smaller, manageable modules. Each module is a self-contained block of code designed to perform a specific task.

Top-Down Design

Key Point
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

Key Point
Routine typeReturn behaviourTypical use
FunctionReturns a valueCalculations / expressions (e.g. average = calcMean(scores))
ProcedureUsually no direct return valuePerforming actions/side effects (e.g. print, write, update)

Worked Example
Parameter Passing

text
// 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)

Definition
An IDE (Integrated Development Environment) is a software suite providing comprehensive tools for software development. It simplifies coding, debugging, and testing processes.

Key IDE Features

Key Point
IDE featureWhat it helps with
SteppingRun line-by-line to trace logic
Variable watchObserve changing values in real time
BreakpointsPause execution at key points
Source editor toolsFaster coding with highlight/autocomplete/bracket matching
Debug toolingLocate runtime errors and inspect state
Integrated toolingRefactoring, compiler/interpreter, version control, project management

Worked Example
IDE Debugging Example

LineCodeVariables/state
1total = 0total = 0
2count = 0total = 0, count = 0
4total = total + scorebreakpoint: inspect values each loop
7average = total / countrisk: division by zero if count == 0
Debug flow:
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

Definition
Object-Oriented Programming (OOP) is a paradigm based on the concept of objects, which are instances of classes. A class defines attributes (state) and methods (behaviour).

Classes and Objects

Key Point
OOP termMeaning
ClassBlueprint defining attributes and methods
ObjectInstance created from a class
InstantiationProcess of creating an object

Encapsulation

Definition
Encapsulation is the practice of keeping an object's state private, accessible only through its public methods. This protects object integrity and hides complexity.

Worked Example
OOP Example: Bank Account

text
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

Exam Tip
Exam Tips for Programming Techniques:
• 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