Learn
8.1.6B.2 | DEFINE AND CALL FUNCTIONS
01 | THE CALLER NEEDS A VALUE
Imagine a ticket program that needs to calculate a cost, compare it with a budget and display it later. A procedure that merely displays the cost cannot supply a result for those calculations. The caller needs the value itself.
A function is a named routine that returns a single value to the point where it is called. A routine is a named group of instructions performing a task. A function call is used within an expression: values and operations evaluated to produce a result.
Think of the call as a request for a result. The function executes its instructions, returns the result, and the calling expression continues using that value.
02 | DEFINE A FUNCTION AND ITS RESULT TYPE
A definition states what the function does. Begin with FUNCTION, its name, any parameters, and RETURNS followed by the result’s data type. Finish with ENDFUNCTION.
A parameter is a named item receiving a supplied value at a call. Number is an INTEGER parameter. The body is the instruction group between FUNCTION and ENDFUNCTION; here it contains RETURN Number * 2.
RETURNS INTEGER declares the result type in the header. RETURN supplies the actual result from the body. These keywords have different jobs.
FUNCTION Double(Number : INTEGER) RETURNS INTEGER RETURN Number * 2 ENDFUNCTION
03 | CALL IT INSIDE AN ASSIGNMENT
In Cambridge pseudocode, a function call belongs in an expression. Do not put CALL before it: CALL invokes a procedure as a complete statement.
At Double(6), six is supplied to Number. RETURN evaluates six times two and sends twelve back. The call is replaced by twelve in the right-hand expression, and the assignment stores twelve in Result.
The definition is placed at the start of the code. Merely defining Double does not perform the calculation; the expression containing the call causes execution of its body.
FUNCTION Double(Number : INTEGER) RETURNS INTEGER RETURN Number * 2 ENDFUNCTION DECLARE Result : INTEGER Result ← Double(6) OUTPUT Result
04 | TRACE THE CALL AND ITS RESULT
The caller is the part of the program making the call. The argument is the value or expression supplied by that caller, also described as a parameter value.
The caller must receive the function’s result before it can finish this assignment. Result is not assigned six simply because six appears in the call. Six is the incoming value; twelve is the returned value.
| Stage | What happens |
|---|---|
| Caller reaches Double(6) | The argument value is 6 |
| Function starts | Parameter Number receives 6 |
| Body evaluates Number * 2 | The calculation produces 12 |
| RETURN executes | 12 is returned to the calling expression |
| Assignment finishes | Result receives 12 |
| OUTPUT Result | The stored value 12 is displayed |
05 | USE THE RESULT IN A LARGER EXPRESSION
The returned value need not be stored on its own. It can become part of a larger calculation. For Total ← Double(6) + 3, Double returns twelve, then the caller adds three and stores fifteen.
A call can also appear in an OUTPUT expression. OUTPUT Double(4) displays eight. The display comes from the caller’s OUTPUT instruction, not from RETURN.
Repeated calls are separate executions. Double(6) and Double(4) run the same definition with different arguments.
DECLARE Total : INTEGER Total ← Double(6) + 3 OUTPUT Total OUTPUT Double(4)
06 | RETURN IS NOT OUTPUT
RETURN provides a result to the caller. OUTPUT communicates information to the user. Returning a value does not itself display it, and displaying a number does not replace the required RETURN in a function.
RETURN ends the current function execution and hands back its result. It does not stop the whole program. The caller continues evaluating the expression that requested the value.
A function that returns a cost can be used even when no display is wanted. The caller might compare the result with a budget or add it to another cost.
| Instruction | Effect |
|---|---|
| RETURN Quantity * Price | Provides the calculated value to the caller |
| Cost ← TicketCost(3, 4.50) | Stores the returned value |
| OUTPUT Cost | Displays the stored value |
07 | MATCH PARAMETERS AND ARGUMENTS
TicketCost needs an INTEGER quantity and a REAL price. The argument positions determine which values belong to which parameters. Its REAL result can be stored in a REAL variable.
TicketCost(3, 4.50) returns 13.5. The caller can supply literals, variables or suitable expressions. With Tickets equal to two, TicketCost(Tickets + 1, 4.50) first evaluates the argument expression to three and returns the same cost.
Match the number, order and types of arguments to the definition. The syllabus permits functions with up to three parameters. A parameter list does not automatically validate that a quantity or price is non-negative; these examples assume suitable inputs.
FUNCTION TicketCost(Quantity : INTEGER, Price : REAL) RETURNS REAL RETURN Quantity * Price ENDFUNCTION DECLARE Tickets : INTEGER DECLARE Cost : REAL Tickets ← 2 Cost ← TicketCost(Tickets + 1, 4.50)
08 | TRY A FUNCTION INSIDE A CALCULATION
Choose a quantity, price and delivery charge. The caller evaluates Total ← TicketCost(Quantity, Price) + Delivery. Predict the returned ticket cost separately from the caller’s final total.
The controls validate the demo’s values. Prices and charges are displayed to two decimal places for readability; formatting is separate from the numeric result returned by the pseudocode function.
09 | A FUNCTION CAN RETURN BOOLEAN
Not every useful result is a number. IsValidScore returns TRUE or FALSE for an INTEGER score. The AND expression itself produces the BOOLEAN value returned.
The caller uses that result as its IF condition. For fifty, both comparisons are TRUE, so the caller outputs “Score accepted”. For one hundred and one, the upper comparison is FALSE, so the caller outputs “Score rejected”.
The function checks only the numeric range. Its INTEGER parameter assumes an integer has already been supplied; it does not convert arbitrary input text.
FUNCTION IsValidScore(Score : INTEGER) RETURNS BOOLEAN
RETURN (Score >= 0) AND (Score <= 100)
ENDFUNCTION
IF IsValidScore(50)
THEN
OUTPUT "Score accepted"
ELSE
OUTPUT "Score rejected"
ENDIF10 | RETURN A RESULT ON EVERY POSSIBLE ROUTE
A function with selection must provide a result whichever route is taken. GradeLabel returns a STRING describing a valid score from zero to one hundred.
There is one RETURN in each final branch. A call returns only the value on the selected route: eighty returns “Distinction”, fifty returns “Pass”, and forty-nine returns “Not a pass”. “Single returned value” does not mean a definition may contain only one RETURN instruction.
These returns cover all possible paths through the selection. Omitting the lowest branch’s RETURN would leave some calls without the required result.
FUNCTION GradeLabel(Score : INTEGER) RETURNS STRING
IF Score >= 80
THEN
RETURN "Distinction"
ELSE
IF Score >= 50
THEN
RETURN "Pass"
ELSE
RETURN "Not a pass"
ENDIF
ENDIF
ENDFUNCTION
OUTPUT GradeLabel(79)11 | A FUNCTION MAY HAVE NO PARAMETERS
A function does not have to receive arguments. It still returns a value. StandardTicketPrice below supplies a fixed REAL value without needing information from the caller.
Cambridge’s no-parameter definition uses the name followed by RETURNS and the result type. The no-parameter function call uses its name as part of an expression, as shown below.
This example is useful for learning the notation. For a simple fixed rule, a named constant may be a simpler design choice. Having no parameters does not make this a procedure: the function still supplies a returned value.
FUNCTION StandardTicketPrice RETURNS REAL RETURN 4.50 ENDFUNCTION DECLARE Price : REAL Price ← StandardTicketPrice OUTPUT Price
12 | A FUNCTION BODY CAN INCLUDE A LOOP
A function can do more than one arithmetic instruction. SumTo adds every INTEGER from one to Limit, then returns the total. Assume Limit is a non-negative INTEGER.
Total is initialised to zero each time the function runs. With Limit three, its values become one, three and six, so the result is six. With Limit zero, the ascending FOR has no iterations and the function returns zero.
RETURN is after NEXT, so the complete loop finishes before the result is returned. Putting RETURN inside the loop would end the function during its first iteration rather than calculate the full total.
FUNCTION SumTo(Limit : INTEGER) RETURNS INTEGER
DECLARE Counter : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR Counter ← 1 TO Limit
Total ← Total + Counter
NEXT Counter
RETURN Total
ENDFUNCTION
OUTPUT SumTo(3)13 | THREE PARAMETERS, ONE RETURNED RESULT
Three INTEGER scores can be supplied to a mean function. The returned mean uses REAL because dividing whole numbers can produce a fractional result.
For scores two, four and nine, the sum is fifteen and the mean is five. For two, four and eight, the result is fourteen divided by three, approximately 4.667. The function does not round or format that value.
The parentheses make the calculation explicit: add all three scores before dividing by three. Writing First + Second + Third / 3 would divide only the third score before adding the others.
FUNCTION MeanScore(First : INTEGER, Second : INTEGER, Third : INTEGER) RETURNS REAL RETURN (First + Second + Third) / 3 ENDFUNCTION DECLARE Average : REAL Average ← MeanScore(2, 4, 9) OUTPUT Average
14 | FIX COMMON FUNCTION ERRORS
Using CALL: write Cost ← TicketCost(3, 4.50), not CALL TicketCost(3, 4.50). The caller must use the function as part of an expression.
Replacing RETURN with OUTPUT: displaying the answer does not supply the result required by the function’s caller.
Missing result on a branch: trace every possible route and check that it returns a suitable value.
Wrong result type: a fractional mean should return REAL, while a validity check should return BOOLEAN. The value returned must match the declared type.
Returning too early: RETURN exits the function. Place it after any loop that must complete before the answer is ready.
15 | DEFINE, TRACE AND TEST
Decide what one result the caller needs. Choose the function’s name, parameter list and return type, then write its body so every possible route provides a result.
For each test, record the argument values, parameter mapping, calculation or decisions inside the body, returned value and the caller’s final use of that value. Test boundaries such as score zero and one hundred, and zero iterations where a loop permits them.
A useful explanation is: “TicketCost returns 13.5, which replaces the call in the expression. The caller then adds the delivery charge of two, resulting in Total equal to 15.5.”
The next lesson explains local and global variables, including which parts of a program can use a declared variable.