Subroutines: Functions and Procedures
What subroutines are
A subroutine is a named block of code that performs a specific task and can be called (run) whenever needed. Subroutines come in two kinds: functions and procedures. They make programs shorter, clearer and easier to maintain.
Why use subroutines?
- Avoid repetition — write the code once, call it many times.
- Break a big problem into smaller parts (decomposition) — each subroutine solves one task.
- Easier to read, test and debug — you can test each subroutine separately.
- Reusable — the same subroutine can be used in other programs.
Functions vs procedures
| Function | Procedure | |
|---|---|---|
| Returns a value? | Yes – gives a result back | No – just performs actions |
| Typical use | Calculate something you use later | Do a task (e.g. print a menu) |
| Example call | total = add(3, 4) | showMenu() |
function add(a, b)
return a + b
endfunction
procedure greet(name)
output "Hello " + name
endprocedure
Parameters and arguments
- A parameter is a variable listed in the subroutine definition — the data it needs to do its job (
aandbabove). - An argument is the actual value you pass in when calling it (
add(3, 4)passes 3 and 4). - Passing data in through parameters makes a subroutine flexible — it works on different values each time.
Return values
A function sends a result back with return. The calling code can store or use it:
answer = add(10, 5) // answer becomes 15
Local vs global variables
- A local variable is created inside a subroutine and only exists there — it can't be seen by the rest of the program.
- A global variable is declared outside all subroutines and can be used anywhere.
- Prefer local variables: they avoid accidental clashes, keep subroutines self-contained, and free memory when the subroutine ends.
Worked example
What does output add(add(2, 3), 4) print, using the add function above?
1. Inner call: add(2, 3) = 5.
2. Outer call: add(5, 4) = 9. ✓
Common mistakes
- Confusing a function (returns a value) with a procedure (doesn't).
- Mixing up parameter (in the definition) and argument (the value passed in).
- Trying to use a local variable outside its subroutine.
Exam tips
- Learn the one-line difference: function returns a value, procedure does not.
- Be ready to explain two benefits of subroutines (e.g. reuse + easier debugging).
- Know why local variables are preferred over global ones.
Key facts to remember
- A subroutine is a named, reusable block of code — a function (returns a value) or a procedure (performs a task).
- Parameters receive data (the passed-in values are arguments); functions send results back with return.
- Local variables exist only inside a subroutine; global ones exist everywhere — locals are safer.