AQA GCSE Computer Science (8525), section 3.2.10 (Structured programming and subroutines (procedures and functions))
What is a subroutine?
A subroutine is a named block of code that does a particular job. It is kept out of line from the main program and is called by writing its name in a statement. Subroutines are also called procedures and functions.
- A procedure carries out a task.
- A function carries out a task and returns a value to the code that called it.
Why use subroutines?
- Reuse: write the code once and call it many times.
- Shorter programs, with less repeated code.
- Easier to test and fix: each subroutine can be tested on its own.
- Easier to read, as a program is split into named parts.
- Several programmers can work on different subroutines.
Parameters
A parameter is a value passed into a subroutine when it is called, so it can work with different data each time. A subroutine can have more than one parameter. (The exam uses the word parameter for both the names in the definition and the values passed.)
SUBROUTINE greet(name)
OUTPUT "Hello " + name
ENDSUBROUTINE
greet("Aisha")
greet("Ben")
Return values
A subroutine returns a value with RETURN. The calling code can then use or store it.
SUBROUTINE area(width, height)
RETURN width * height
ENDSUBROUTINE
room ← area(4, 3)
OUTPUT room
Python
def greet(name):
print("Hello", name)
def area(width, height):
return width * height
greet("Aisha")
room = area(4, 3)
print(room) # 12
Passing data
| Direction | How |
|---|---|
| Into a subroutine | parameters |
| Out of a subroutine | return value |
Common mistake: writing a function that prints the answer when it should RETURN it. If the result is needed elsewhere in the program, it must be returned. Also, the order and number of values in the call must match the parameters.
Exam tip: when asked for advantages of subroutines, give clear separate points: the code can be reused, the program is shorter, and each part is easier to test.
Check yourself
What is the difference between a procedure and a function?
A function returns a value to the calling code, whereas a procedure does not.
How does a subroutine receive data from the main program?
Through its parameters.
Give two advantages of using subroutines.
Code can be reused, and each part can be tested separately (also: shorter programs, easier to read).