CIE AS & A Level Computer Science, section 11.3 (Structured programming)
What a function is
A function is a named block of code that returns a single value to the place it was called. A function call can be used in an expression: the return value replaces the call.
Defining and using
FUNCTION Area(Width : REAL, Height : REAL) RETURNS REAL
RETURN Width * Height
ENDFUNCTION
Result ← Area(4, 3)
OUTPUT "The area is ", Area(5, 2)
Python
def area(width, height):
return width * height
result = area(4, 3)
print(result, area(5, 2) + 1) # 12 11
A function that makes a decision
FUNCTION IsEven(Number : INTEGER) RETURNS BOOLEAN
RETURN Number MOD 2 = 0
ENDFUNCTION
IF IsEven(Count) THEN
OUTPUT "even"
ENDIF
When to use a function
Use a function when the task calculates and gives back a result: finding an average, checking whether a value is valid, or converting a unit. If it only displays output, use a procedure.
Terms
| Term | Meaning |
|---|---|
| Function header | the line with the name, parameters and return type |
| Interface | the name, parameters and return type seen by the caller |
| Parameter | the variable named in the definition |
| Argument | the actual value passed in the call |
| Return value | the value sent back to the caller |
Libraries supply many ready-made functions, such as those for strings.
Common mistake: forgetting the RETURN statement, or writing code after it that never runs. Also, a function call is part of an expression, so the result must be used (stored, output or tested) and not thrown away.
Exam tip: include the return type in the header and a RETURN statement on every path. Say why a function is suitable: it returns a value that is used in an expression.
Check yourself
What does a function return?
A single value, which replaces the function call.
What is the difference between a parameter and an argument?
A parameter is the variable named in the function definition; an argument is the value passed in when it is called.
Write a function header that returns the average of two REAL numbers.
FUNCTION Average(A : REAL, B : REAL) RETURNS REAL.