Functions
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(Number : INTEGER) RETURNS INTEGER
RETURN Number * Number
ENDFUNCTION
OUTPUT Square(6) // → 36
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.
FUNCTION Square(Number : INTEGER) RETURNS INTEGER
RETURN Number * Number
ENDFUNCTION
DECLARE Answer : INTEGER
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(Number : INTEGER) RETURNS BOOLEAN
RETURN Number > 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.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Define FUNCTION Square(Number : INTEGER) RETURNS INTEGER that returns Number × Number, then output Square(5) (it is 25).
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Define FUNCTION Add(FirstNumber : INTEGER, SecondNumber : INTEGER) RETURNS INTEGER that returns FirstNumber + SecondNumber, then output Add(3, 4) (it is 7).
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Define FUNCTION IsEven(Number : INTEGER) RETURNS BOOLEAN that returns TRUE when Number is even, then output IsEven(8) (it is TRUE).
Click Run to see the output here.