H446/01 · Computer SystemsSection 1.2

1.2.4 Types of programming language

High vs low level, imperative vs declarative, assembly language, addressing modes (immediate, direct, indirect, indexed)

📚1.2.4 Types of Programming Language

1.2.4(a) Programming Paradigms

Different problems require different approaches to solve them efficiently. Programming paradigms provide frameworks for thinking about and structuring solutions.

Definition
A programming paradigm is a fundamental style or approach to programming that provides a framework for how programs are structured and how problems are solved.

Imperative vs Declarative

Key Point
Two Main Categories:

Imperative Paradigms - Focus on HOW to solve a problem
• You specify the exact steps the computer must take
• Like giving detailed directions: "Turn left, walk 50m, turn right..."
• Examples: Procedural, Object-Oriented

Declarative Paradigms - Focus on WHAT the outcome should be
• You describe what you want, not how to get it
• Like saying: "Get me to the train station"
• Examples: Functional, Logic programming, SQL


1.2.4(b) Procedural Languages

Procedural programming is one of the most common paradigms, especially for learning to program.

Definition
Procedural programming structures programs as a sequence of procedures (functions) that operate on data. The program flows from top to bottom, calling procedures as needed.

Key Point
Key Features of Procedural Programming:
• Programs are sequences of instructions
• Uses the three constructs: sequence, selection, iteration
• Code organised into procedures/functions
• Data and procedures are separate
• Top-down design approach
• Examples: C, Pascal, Python (can be procedural)

Procedural Approach to Calculate Grades:

text
// Data is separate from procedures
studentScores = [85, 72, 91, 68, 77]

// Procedure to calculate average
function calculateAverage(scores):
    total = 0
    for each score in scores do
        total = total + score
    end for
    return total / length(scores)
end function

// Procedure to determine grade
function getGrade(average):
    if average >= 70 then
        return "A"
    elseif average >= 60 then
        return "B"
    elseif average >= 50 then
        return "C"
    else
        return "Fail"
    end if
end function

// Main program flow
avg = calculateAverage(studentScores)
grade = getGrade(avg)
print("Average: " + avg + ", Grade: " + grade)

Exam Tip
When to use Procedural:
• Small to medium programs
• Problems with clear step-by-step solutions
• Learning to program
• Scripts and automation tasks


1.2.4(c) Assembly Language

Assembly language provides the closest human-readable representation of what the CPU actually executes.

Definition
Assembly language is a low-level programming language with a strong correspondence to machine code instructions. It uses mnemonics (short codes) instead of binary.

Relationship to Machine Code

Key Point
Assembly vs Machine Code:
• Machine code: Binary instructions CPU directly executes (e.g., 00010101)
• Assembly: Human-readable mnemonics (e.g., ADD, LDA, STA)
• One assembly instruction = typically one machine code instruction
• Assembler converts assembly → machine code

The Same Instruction:

assembly
Machine Code: 0101 0011 0100
Assembly:     LDA 52
Meaning:      Load value from address 52 into accumulator

Why Use Assembly?

Pros & Cons
Pros & Cons (Assembly Language):

AdvantagesDisadvantages
Maximum efficiency - no compiler overheadDifficult to write and debug
Direct hardware controlNot portable (CPU-specific)
Precise timing controlTime-consuming development
Small code sizeEasy to make errors
Used in device drivers, embedded systems, OS kernelsHard to maintain


1.2.4(d) Modes of Addressing Memory

When an instruction needs to access data, it must specify WHERE that data is. Different addressing modes provide different ways to specify the location.

Definition
Addressing modes are the different methods used to specify the location of an operand (the data an instruction operates on).

Immediate Addressing

Definition
In immediate addressing, the operand IS the actual value to be used - no memory lookup needed.

Immediate Addressing Examples:

assembly
ADD #5    // Add the literal value 5 to accumulator
LDA #100  // Load the literal value 100 into accumulator

The # symbol indicates immediate addressing. The value 5 or 100 is used directly.

Direct Addressing

Definition
In direct addressing, the operand specifies the memory address where the data is stored.

Direct Addressing Examples:

assembly
ADD 50    // Add the value STORED AT address 50 to accumulator
LDA 100   // Load the value STORED AT address 100 into accumulator

If address 50 contains the value 7, then ADD 50 adds 7.

Indirect Addressing

Definition
In indirect addressing, the operand points to a memory location that contains the ADDRESS of the actual data.

Worked Example: Indirect Addressing

Key Point
Memory addressValue stored
5075
7542

assembly
LDA @50    // indirect addressing, @ symbol

Key Point
Step-by-step:
1. Look at address 50 → find value 75
2. Use 75 as the actual address
3. Look at address 75 → find value 42
4. Load 42 into accumulator

Result: Accumulator = 42

Indexed Addressing

Definition
In indexed addressing, the final address is calculated by adding a base address to a value in an index register.

Worked Example: Indexed Addressing

Key Point
ItemValue
Base address100
Index register (X)3
Effective address100 + 3 = 103

assembly
LDA 100,X

Action: Load value from address 103 into accumulator.

Why is this useful? Perfect for arrays - the base address is where the array starts, and the index moves through each element.

Key Point
X valueInstructionAddress usedValue loaded
0LDA 100,X10010
1LDA 100,X10120
2LDA 100,X10230

Addressing Modes Summary

Key Point
Immediate
• Operand Contains: The actual value
• Example: ADD #5
• Use Case: Constants, fixed values

Direct
• Operand Contains: Address of data
• Example: ADD 50
• Use Case: Simple variables

Indirect
• Operand Contains: Address of address
• Example: ADD @50
• Use Case: Pointers, dynamic access

Indexed
• Operand Contains: Base + index
• Example: ADD 100,X
• Use Case: Arrays, tables

Exam Tip
Memory Tip:
• Immediate = the value is RIGHT THERE in the instruction
• Direct = go DIRECTLY to that address for the value
• Indirect = indirect route - address gives you another address
• Indexed = base + index (like array access)


1.2.4(e) Object-Oriented Languages (OOP)

Object-Oriented Programming is a paradigm that organises code around objects - entities that combine data and behaviour.

Definition
Object-Oriented Programming (OOP) is a paradigm based on the concept of objects, which contain both data (attributes) and code (methods) that operate on that data.

Classes and Objects

Definition
A class is a blueprint or template that defines what attributes and methods objects of that type will have.

An object is a specific instance of a class - a real entity created from the blueprint.

Worked Example: Class and Object

text
// CLASS - the blueprint
class Dog:
    // Attributes (data)
    private name
    private breed
    private age
    
    // Constructor - creates new objects
    public procedure new(givenName, givenBreed, givenAge):
        name = givenName
        breed = givenBreed
        age = givenAge
    end procedure
    
    // Methods (behaviour)
    public procedure bark():
        print(name + " says: Woof!")
    end procedure
    
    public function getAge():
        return age
    end function
end class

// OBJECTS - instances of the class
myDog = new Dog("Rex", "German Shepherd", 3)
yourDog = new Dog("Bella", "Labrador", 5)

// Using the objects
myDog.bark()             // Output: Rex says: Woof!
print(yourDog.getAge())  // Output: 5

Encapsulation

Definition
Encapsulation is the bundling of data (attributes) and methods that operate on that data within a single unit (class), while restricting direct access to some components.

Key Point
Public vs Private:
• Private attributes/methods: Only accessible within the class
• Public attributes/methods: Accessible from outside the class

Why Encapsulate?
• Protects data from invalid modifications
• Hides implementation details
• Makes code easier to maintain
• Provides controlled access through methods (getters/setters)

Encapsulation Example:

text
class BankAccount:
    private balance    // Cannot be accessed directly from outside
    
    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
account = new BankAccount()
// account.balance = 1000000    // ERROR - balance is private!
account.deposit(500)            // OK - uses public method
print(account.getBalance())     // OK - uses public method

Inheritance

Definition
Inheritance allows a new class (subclass/child) to inherit attributes and methods from an existing class (superclass/parent), promoting code reuse.

Worked Example: Inheritance

text
// SUPERCLASS (parent)
class Animal:
    protected name
    protected age
    
    public procedure makeSound():
        print("Some sound")
    end procedure
end class

// SUBCLASS (child) - inherits from Animal
class Dog inherits Animal:
    private breed
    
    // Override parent method
    public procedure makeSound():
        print(name + " barks: Woof!")
    end procedure
    
    // Additional method specific to Dog
    public procedure fetch():
        print(name + " fetches the ball")
    end procedure
end class

// SUBCLASS (child)
class Cat inherits Animal:
    public procedure makeSound():
        print(name + " meows: Meow!")
    end procedure
end class

// Usage
myDog = new Dog()
myDog.name = "Rex"        // Inherited from Animal
myDog.makeSound()         // Output: Rex barks: Woof!
myDog.fetch()             // Dog-specific method

myCat = new Cat()
myCat.name = "Whiskers"   // Inherited from Animal
myCat.makeSound()         // Output: Whiskers meows: Meow!

Polymorphism

Definition
Polymorphism means "many forms" - it allows objects of different classes to be treated as objects of a common parent class, with each responding to methods in their own way.

Polymorphism Example:

text
// Both Dog and Cat inherit from Animal
animals = [new Dog("Rex"), new Cat("Whiskers"), new Dog("Bella")]

// Polymorphism - same method call, different behaviour
for each animal in animals do
    animal.makeSound()
end for

// Output:
// Rex barks: Woof!
// Whiskers meows: Meow!
// Bella barks: Woof!

// The code doesn't need to know the specific type -
// each object responds appropriately

OOP Principles Summary

Key Point
Encapsulation
• Description: Bundle data and methods, hide internals
• Benefit: Data protection, maintainability

Inheritance
• Description: Child classes inherit from parent
• Benefit: Code reuse, hierarchy

Polymorphism
• Description: Same interface, different implementations
• Benefit: Flexibility, extensibility

Abstraction
• Description: Hide complex details, show only essentials
• Benefit: Simplicity, focus

Exam Tip
OOP vs Procedural:
• OOP: Data and methods together in objects
• Procedural: Data and procedures separate
• OOP better for: Large projects, code reuse, modelling real-world entities
• Procedural better for: Small scripts, simple programs, learning