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
• Need to return multiple values
• Modifying large data structures (avoid copying)
• When the subroutine must change the original
Passing Parameters by Value and by Reference
| Feature | By value | By reference |
|---|---|---|
| What is passed | A copy of the value | The address of the variable |
| Effect on the original | None | Changed by the subroutine |
| Memory | Extra memory is needed for the copy | Nothing is copied, which matters for a large array |
| Typical use | Data the subroutine only needs to read | Data the subroutine must update, such as an array to be sorted |
OCR pseudocode states how each parameter is passed by writing byVal or byRef after its name.
procedure update(score:byVal, total:byRef):
score = score + 10
total = total + score
end procedure
points = 5
sum = 100
update(points, sum)
print(points) // 5: only the copy was changed
print(sum) // 115: the original was changed