Programming · 4 question types
Past paper frequency (2018 to 2024)
This topic accounts for approximately 4% of your exam marks.
Writing and calling procedures/functions with parameters is tested in Paper 2.
A function is a named block of code that performs a calculation and returns a value to the place it was called from. It is called directly inside an expression, not with
CALL.
A function with no parameters:
FUNCTION FunctionName RETURNS TYPE
// statements
RETURN Value
ENDFUNCTION
A function with parameters:
FUNCTION FunctionName(Param1 : TYPE, Param2 : TYPE, ...) RETURNS TYPE
// statements
RETURN Value
ENDFUNCTION
Two extra things compared with a procedure:
RETURNS <data type> appears at the end of the first line, declaring what type of value the function gives back.RETURN <value> statement specifies the value to send back. The function ends as soon as a RETURN runs.A function is not called with CALL. It is used inside an expression, in any place a value would normally go:
Result ← FunctionName(Value1, Value2)
OUTPUT FunctionName(5, 3)
IF FunctionName(X) > 0 THEN
...
ENDIF
The expression FunctionName(...) evaluates to whatever the function returned.
Example — calculate-area function
FUNCTION CalculateArea(Length : INTEGER, Width : INTEGER) RETURNS INTEGER
Area ← Length * Width
RETURN Area
ENDFUNCTION
// Main program: use the returned value
OUTPUT CalculateArea(5, 3) // outputs 15
// Or save it for later use
Result ← CalculateArea(10, 20)
OUTPUT "The area is ", Result // outputs "The area is 200"
The function gives back Area to the caller. The caller can output it, save it in a variable, use it inside another calculation, or pass it as an argument to a different sub-program.
Choose a function when the sub-program's job is to calculate and produce a value:
TRUE or FALSE).