0984

Procedures and Functions

Programming · 4 question types

Exam Frequency Analysis

Past paper frequency (2018 to 2024)

This topic accounts for approximately 4% of your exam marks.

stable
Rare
Stable4%

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.

Defining a function

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:

  1. The keyword RETURNS <data type> appears at the end of the first line, declaring what type of value the function gives back.
  2. Inside the body, a RETURN <value> statement specifies the value to send back. The function ends as soon as a RETURN runs.

Calling a function

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.

When to use a function

Choose a function when the sub-program's job is to calculate and produce a value:

  • Calculate the area of a rectangle.
  • Convert a temperature from Celsius to Fahrenheit.
  • Return the largest of a list of numbers.
  • Look up a student's grade from their mark.
  • Check whether a password meets the validation rules (returning TRUE or FALSE).