Functions
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(Number : INTEGER) RETURNS INTEGER
RETURN Number * Number
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
A definition does not display a result by itself. Trace a call such as OUTPUT Max(4, 7): the function returns once, and the caller outputs once. An extra output inside the function changes the required output.
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.
Independent transfer
The final task has no supplied algorithm. Plan its inputs, processing and outputs, then solve it before opening support. Check more than the sample case.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Write Square so that OUTPUT Square(6) prints 36.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Write Max to return the larger of two integers. OUTPUT Max(10, 24) should print 24.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Write only FUNCTION IsEven(Value : INTEGER) RETURNS BOOLEAN. Return TRUE exactly when Value is even.
Click Run to see the output here.