Functions
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A function returns one value
- A function is like a procedure, and it also hands one value back.
- The definition says the type of that value:
RETURNS INTEGER. RETURNsets the value. It is normally the last line of the function.
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION
OUTPUT Square(6)
Do not write CALL
- A function is used inside an expression, where its returned value is needed.
CALLis only for a procedure.- Parameters of a function are passed by value. The guide says not to use
BYREFon a function.
FUNCTION Max(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER
IF Number1 > Number2 THEN
RETURN Number1
ELSE
RETURN Number2
ENDIF
ENDFUNCTION
OUTPUT Max(10, 24)
Common mistakes
RETURNbelongs inside the function. Outside it, there is nothing to return to.- The call
Square(6)is not a complete statement on its own.OUTPUT Square(6)is.
Now you try
- Write a function and use its result in
OUTPUT.
Write Square so that OUTPUT Square(6) prints 36.
Click Run to see the output here.
Write Max to return the larger of two integers. OUTPUT Max(10, 24) should print 24.
Click Run to see the output here.