CIE AS & A Level Computer Science, section 11.3 (Structured programming)
What a procedure is
A procedure is a named block of code that carries out a task. It is called by name whenever the task is needed. It does not return a value. A procedure may have none, one or more parameters.
Defining and calling
PROCEDURE ShowMenu
OUTPUT "1. Play"
OUTPUT "2. Quit"
ENDPROCEDURE
PROCEDURE Greet(Name : STRING)
OUTPUT "Hello ", Name
ENDPROCEDURE
CALL ShowMenu
CALL Greet("Aisha")
Python
def show_menu():
print("1. Play")
print("2. Quit")
def greet(name):
print("Hello", name)
show_menu()
greet("Aisha") # Hello Aisha
When to use a procedure
Use a procedure when a task is repeated or when you want to break the program into sections (decomposition), and the section does not need to give a value back to the calling code. Examples: displaying a menu, printing a report, drawing a shape.
Benefits
- Code is reused, so the program is shorter.
- It is easier to test and maintain.
- Different people can write different procedures.
- The main program is easier to follow.
Terms
- Procedure header: the first line, with the name and parameters.
- Interface: the name, parameters and what the procedure does, which is all the caller needs to know.
Common mistake: expecting a procedure to return a value. A procedure performs actions. If you need a value back, use a function. Also, call a procedure with CALL in pseudocode, and use the same number of arguments as parameters.
Exam tip: define the procedure with a clear name and its parameters with their data types, then show a CALL with suitable arguments. State why a procedure (not a function) is suitable.
Check yourself
What is the difference between a procedure and a function?
A function returns a value and is used in an expression, whereas a procedure carries out a task and does not return a value.
Write the statement to call a procedure `Greet` with the argument "Ben".
CALL Greet("Ben").
Give one benefit of using procedures.
Code can be reused, and the program is easier to test and maintain.