Multiple choiceQuestion 1 · Recall
Loading…
By the end you can write a function in 9618 pseudocode, explain how its call is replaced by its value, and say where in an algorithm a function is the right choice rather than a procedure.
A procedure is good at doing things: print a receipt, read a record, draw a heading.
But most programs also need answers. How much is 17% of £84.40? Is this password long enough? What is the average of these 40 marks?
An answer is useless sitting inside a subprogram. You need it back, so you can store it, print it, or compare it. Something has to hand it over.
A function is a subprogram built for exactly that: it works out one value and returns it to whoever asked.
Function
A function is a named block of statements that returns exactly one value to the statement that called it.
It is defined between FUNCTION and ENDFUNCTION, the header declares the type of the
value it returns, and the value is handed back with a RETURN statement.
FUNCTION Square(Number : INTEGER) RETURNS INTEGER
RETURN Number * Number
ENDFUNCTION
Read the header in three pieces:
FUNCTION Square — the name.(Number : INTEGER) — the information it needs (parameters are the next lesson).RETURNS INTEGER — the type of value it will hand back, so the rest of the program knows
what to expect.Now call it inside an expression:
Answer ← Square(7)
The call Square(7) is worked out first. Number becomes 7, RETURN 7 * 7 hands back 49,
and the line the program is running effectively becomes
Answer ← 49
That replacement is the whole idea of a function. Because the call turns into a value, a function call can sit anywhere a value is allowed:
OUTPUT Square(5) // prints 25
IF Square(Side) > 100 THEN // the comparison uses the returned value
...
ENDIF
Total ← Square(3) + Square(4) // two calls, added
You never write CALL Square(7). CALL is for procedures, which hand nothing back.
RETURN value performs two actions in one statement.
That second effect is useful. A function can check several cases and return as soon as it has the answer:
FUNCTION GradeName(Mark : INTEGER) RETURNS STRING
IF Mark >= 80 THEN
RETURN "A"
ENDIF
IF Mark >= 70 THEN
RETURN "B"
ENDIF
RETURN "U"
ENDFUNCTION
For Mark = 85 the first RETURN fires and the function stops there. The later checks
never run, which is both correct and quicker.
Every possible path through the function must reach a RETURN. If one path falls off the
end without returning, the function has no value to hand back.
Worked example: Worked example — Celsius to Fahrenheit
Write a function that converts a temperature in degrees Celsius to degrees Fahrenheit, using , and show it being used to print a converted value.