Functions
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A FUNCTION returns a value
- A function works something out and hands back a value with
RETURN. RETURNS(in the header) states the type of value it gives back.
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION
OUTPUT Square(6) // → 36
Explore
Run, then RETURN a value
A FUNCTION runs its steps, then RETURNs a value you can use in an expression.
Use the returned value
- Call a function inside an expression, or store its result in a variable.
Answer ← Square(4)
OUTPUT Answer + 1 // → 17
A function can return a Boolean
- The result can be a
BOOLEAN— handy for a yes/no test.
FUNCTION IsPositive(N : INTEGER) RETURNS BOOLEAN
RETURN N > 0
ENDFUNCTION
OUTPUT IsPositive(5) // → TRUE
Watch out
- A procedure does something; a function returns a value you then use.
- Every path through a function must reach a
RETURN.
Common mistakes
FUNCTION name(...) RETURNS TYPE ... RETURN value ... ENDFUNCTION.- A function must
RETURNa value.
Now you try
- Define a function with
RETURNSandRETURN. - Press Check answer to test it.
Define FUNCTION Square(N : INTEGER) RETURNS INTEGER that returns N × N, then output Square(5) (it is 25).
Click Run to see the output here.
Define FUNCTION Add(a : INTEGER, b : INTEGER) RETURNS INTEGER that returns a + b, then output Add(3, 4) (it is 7).
Click Run to see the output here.
Define FUNCTION IsEven(N : INTEGER) RETURNS BOOLEAN that returns TRUE when N is even, then output IsEven(8) (it is TRUE).
Click Run to see the output here.