What is a Subroutine?
A subroutine is a named block of code that performs a specific task. You define it once and call it as many times as needed from anywhere in your program. This is called code reuse.
There are two types of subroutine in AQA:
| Type | Returns a value? | Called using | AQA keyword |
| Procedure | No | Name only | SUBROUTINE / ENDSUBROUTINE |
| Function | Yes (via RETURN) | Name in expression | SUBROUTINE / RETURN / ENDSUBROUTINE |
Why Use Subroutines?
- Code reuse — write once, call many times
- Decomposition — break a large problem into smaller manageable parts
- Easier to test — each subroutine can be tested independently
- Easier to maintain — fix a bug once in the subroutine, not in 10 places
- Readability — meaningful subroutine names make code self-documenting
Procedures (no return value)
A procedure performs an action but does not send back a result. It is called by name.
SUBROUTINE greetUser()
OUTPUT "Welcome to CSZone!"
ENDSUBROUTINE
// Calling the procedure:
greetUser() // Outputs: Welcome to CSZone!
greetUser() // Can call it multiple times
Procedure with parameters
SUBROUTINE printBorder(length)
FOR i ← 1 TO length
OUTPUT "*"
ENDFOR
ENDSUBROUTINE
printBorder(10) // Prints 10 stars
printBorder(5) // Prints 5 stars
Functions (return a value)
A function computes a value and returns it to the calling code using RETURN. The returned value can be stored in a variable or used directly.
SUBROUTINE square(n)
RETURN n * n
ENDSUBROUTINE
result ← square(5) // result = 25
OUTPUT square(3) // Outputs: 9
OUTPUT square(7) // Outputs: 49
Function with multiple parameters
SUBROUTINE calculateAverage(a, b, c)
total ← a + b + c
RETURN total / 3
ENDSUBROUTINE
avg ← calculateAverage(80, 90, 70)
OUTPUT "Average: " + str(avg) // Average: 80.0
Calling Pattern
When a subroutine is called, execution jumps to the subroutine, runs its code, then returns to the line after the call. Functions additionally send back a return value.
// Main program flow:
OUTPUT "Start"
greetUser() // ← jumps to subroutine, then returns here
OUTPUT "End"
Exam tip: In AQA, BOTH procedures and functions use SUBROUTINE...ENDSUBROUTINE. The difference is that functions have a RETURN statement. When asked to write a function, always include RETURN with the result.
⚠️ Common Mistakes
- Forgetting RETURN in a function — without it, nothing is sent back
- Calling a function without using its return value — result is lost
- Not calling the subroutine — defining it does nothing on its own
- Confusing procedure (does something) with function (calculates something)