Procedures, functions and structured programming
Procedures, functions and structure
- Structured programming builds a program from small named subroutines, each with one job.
- This is decomposition in code — easier to read, reuse and test.
- The key distinction: a procedure does an action; a function returns a value.
Procedures vs functions
PROCEDURE Greet(name : STRING)
OUTPUT "Hello, ", name
ENDPROCEDURE
CALL Greet("Ada")
FUNCTION Square(x : INTEGER) RETURNS INTEGER
RETURN x * x
ENDFUNCTION
result ← Square(5) + 1 // 26
- A procedure performs an action and returns nothing; a function returns a value used in an expression.
The key difference between a procedure and a function is that a function:
A function returns a value (used in an expression); a procedure performs an action and returns nothing.
Parameters
- A parameter is the variable a subroutine declares; the argument is the value the caller supplies.
- Pass by value — the routine gets a copy; changes inside don't affect the caller (use for read-only inputs).
- Pass by reference (
BYREF) — the routine gets a reference; changes do affect the caller (use to update a value, e.g.Swap).
When a parameter is passed by value, changes made inside the subroutine:
Pass by value copies the argument, so the original is untouched. Pass by reference would affect the caller.
You need a Swap procedure to actually change the caller's two variables. You should pass them:
To update the caller's variables, pass by reference so the routine works on the originals.
Scope and when to use a subroutine
- A local variable exists only inside its subroutine; a global is visible everywhere. Prefer locals + parameters — globals make code hard to follow and test.
- Use a subroutine when logic appears in more than one place, a block has a clear named purpose, or you want to test a piece in isolation.
A local variable:
A local variable's scope is its own subroutine; a global is visible everywhere (and best avoided where possible).
A good reason to write a subroutine is that:
Subroutines remove duplication, give a named purpose, and can be tested in isolation.
Writing efficient pseudocode
- Move invariants out of loops — compute a value that doesn't change once, before the loop.
- Exit a loop early when the answer is found (stop a linear search at the first match).
- Use meaningful names (
numberOfPupils, notn) and initialise variables before use.
To make a loop more efficient, a value that does not change with the loop counter should be:
Hoisting a loop invariant out avoids recomputing the same value on every iteration.
You've got it
- a procedure does an action (no return); a function returns a value
- pass by value = a copy (caller unchanged); pass by reference = changes affect the caller
- prefer local variables + parameters over globals
- efficiency: hoist invariants out of loops, exit early, use meaningful names