A procedure is a named block of code that performs a task. It does not return a value. Called using CALL. Helps avoid repeating code (DRY — Don't Repeat Yourself).
// Call the procedure CALL PrintHeader("School Report") CALL PrintHeader("Attendance")
Functions
Procedures that Return a Value
A function is a named block of code that performs a calculation and returns a value. Declared with FUNCTION...RETURNS type; uses RETURN to send back the result.
// Define a function FUNCTION Square(n : INTEGER) RETURNS INTEGER RETURN n * n ENDFUNCTION
FUNCTION Max(a, b : INTEGER) RETURNS INTEGER IF a >= b THEN RETURN a ELSE RETURN b ENDIF ENDFUNCTION
// Call a function OUTPUT Square(5) // outputs 25 OUTPUT Max(8, 3) // outputs 8
Parameters & Variable Scope
Passing Data & Variable Visibility
Parameters: values passed into a procedure/function. The procedure receives copies (pass by value) — changes inside don't affect the original variable.
Local variables: declared inside a subroutine — only exist while it runs. Global variables: declared outside, accessible everywhere — use sparingly.
Advantages of subroutines: code reuse; easier to test; easier to read; team can work on different subroutines independently
Exam Practice
Have a go at this question
Cambridge IGCSE 0478 style
Write a FUNCTION called CalculateArea that takes length and width as REAL parameters and returns the area (length × width) as a REAL. Show how you would call it and output the result.
4 marks
FUNCTION CalculateArea(length, width : REAL) RETURNS REAL RETURN length * width ENDFUNCTION
OUTPUT CalculateArea(5.0, 3.2) // outputs 16.0
Key Takeaways
What to Remember
PROCEDURE: named code block — no return value; called with CALL ProcedureName()
FUNCTION: returns a value with RETURN; declared with RETURNS data_type
Parameters: data passed into subroutines; local variables only exist inside their subroutine
Benefits: reuse, easier testing, readability, team collaboration, reduced duplication