A-Level Computer Science / Unit 11: Structured Programming

11.3.2 Functions and Return Values

πŸ”’ Lesson slides are available to signed-in users. Sign in

11.3.2 Functions and Return Values

A function is a named subroutine that produces one value for its caller. Because it produces a value, a function call can appear inside an assignment, calculation, output statement or Boolean expression.

This page focuses on function definitions, calls, return values and local processing. Parameters are introduced where they help explain realistic functions, while detailed parameter-passing mechanisms are developed in 11.3.3.

By the end of this section, you should be able to:

  • Define the term function.
  • Explain the difference between a procedure and a function.
  • Identify a function header, interface, body and end marker.
  • Specify the data type returned by a function.
  • Write a function containing a suitable RETURN statement.
  • Explain how a returned value replaces a function call.
  • Use a function call within an assignment or expression.
  • Use functions that return numeric, string or Boolean values.
  • Trace parameters, local variables and a returned value.
  • Recognise that executing RETURN immediately ends the function call.
  • Choose between a procedure and a function for a given task.
  • Avoid unnecessary repeated function calls.
A complete definition should include three ideas: a function is a named subroutine, it returns one value, and that value can be used in an expression.

What Is a Function?

A function performs a defined task and sends one result back to the point from which it was called.

Function: a named subroutine that returns one value to its caller.

Simple function with no parameters

FUNCTION GetDefaultLevel() RETURNS INTEGER
    RETURN 4
ENDFUNCTION

The function does not produce output by itself. It produces the integer value 4 for use by the calling expression.

CurrentLevel ← GetDefaultLevel()

After the function returns, the assignment behaves as:

CurrentLevel ← 4
Common misconception: returning a value is different from displaying it. RETURN 4 sends the value to the caller; OUTPUT 4 displays it to the user.

Procedure or Function?

Feature Procedure Function
Primary purpose Perform a task Calculate, derive or select a value
Returned data value Not returned directly Returns one value
Typical pseudocode use CALL DisplayMenu Area ← CalculateArea(7, 4)
Can appear in an expression? No Yes
Header includes return type? No Yes
Closing keyword ENDPROCEDURE ENDFUNCTION

Procedure example

PROCEDURE DisplayMenu
    OUTPUT "1. Add record"
    OUTPUT "2. Edit record"
    OUTPUT "3. Exit"
ENDPROCEDURE

CALL DisplayMenu

Function example

FUNCTION CalculateArea(Width : INTEGER,
                       Height : INTEGER) RETURNS INTEGER
    RETURN Width * Height
ENDFUNCTION

PanelArea ← CalculateArea(7, 4)
Choose a function when the caller needs a value. Choose a procedure when the main purpose is to carry out an action without producing a direct result for an expression.

The Parts of a Function

FUNCTION CalculateArea(Width : REAL,
                       Height : REAL) RETURNS REAL
    DECLARE Area : REAL

    Area ← Width * Height

    RETURN Area
ENDFUNCTION
Part Example Purpose
Function header FUNCTION CalculateArea(...) RETURNS REAL Identifies the function, its inputs and its return type
Function name CalculateArea Identifier used in the function call
Parameter list Width : REAL, Height : REAL Names the data received by the function
Return type RETURNS REAL States the data type of the result
Function body Declaration, calculation and return statement Contains the processing performed during the call
Return statement RETURN Area Sends the result to the caller
End marker ENDFUNCTION Marks the end of the definition
Common mistake: do not omit the parentheses from a parameterless function header or call. Write GetDefaultLevel(), not GetDefaultLevel.

The Function Interface

The interface describes how another part of the program can use the function. It includes the function name, its parameters and the type of value returned.

Function interface: the information needed to call a function correctly, including its name, parameter requirements and return type.
FUNCTION CalculateArea(Width : REAL,
                       Height : REAL) RETURNS REAL
Interface element Meaning
CalculateArea Name used by the caller
Width : REAL First required input
Height : REAL Second required input
RETURNS REAL Type of value produced
PanelArea ← CalculateArea(7.5, 4.2)

In this call, 7.5 and 4.2 are arguments supplied to the function. Detailed parameter and argument terminology continues in the next section.

Before using a function, check the number and types of arguments and the type of value that will be returned.

How a Return Value Replaces a Function Call

FUNCTION GetBonus() RETURNS INTEGER
    RETURN 6
ENDFUNCTION

FinalScore ← 14 + GetBonus()
Stage What happens?
1. Call encountered Evaluation pauses when the program reaches GetBonus()
2. Function executes The statements in GetBonus run
3. Value returned The function returns 6
4. Call replaced The expression becomes 14 + 6
5. Expression completed FinalScore receives 20
14 + GetBonus() β†’ 14 + 6 β†’ 20
Common misconception: the returned value does not have to be assigned immediately to a separate variable. It can replace the call wherever that call appears in a valid expression.

Using Function Calls in Expressions

A function call can be placed wherever a value of its return type would be valid.

Assignment

PanelArea ← CalculateArea(7, 4)

Arithmetic expression

TotalSpace ← ExistingSpace + CalculateArea(7, 4)

Output statement

OUTPUT "Area: ", CalculateArea(7, 4)

Boolean condition

IF IsSafeReading(CurrentReading) = TRUE
THEN
    OUTPUT "Reading accepted"
ENDIF

Argument supplied to another function

Category ← GetAreaCategory(CalculateArea(7, 4))
Incorrect:
CALL CalculateArea(7, 4)
A function call is used as part of an expression. The keyword CALL is used for procedures.
To trace a nested expression, evaluate the innermost function call first and replace it with its returned value.

Function Return Types

The value returned must be compatible with the type declared in the function header.

Function purpose Possible return type Example result
Count matching records INTEGER 12
Calculate an average REAL 18.75
Create a status label STRING "Available"
Test whether data is acceptable BOOLEAN TRUE
Select a single code CHAR 'H'

Boolean function

FUNCTION IsSafeReading(Reading : INTEGER) RETURNS BOOLEAN
    RETURN Reading >= 20 AND Reading <= 80
ENDFUNCTION

String function

FUNCTION GetAvailability(InStock : BOOLEAN) RETURNS STRING
    IF InStock = TRUE
    THEN
        RETURN "Available"
    ELSE
        RETURN "Unavailable"
    ENDIF
ENDFUNCTION
Type mismatch: a function declared with RETURNS INTEGER should not return a string such as "Twelve".

Return Statements and Alternative Paths

A function can contain selection. Every possible execution path should produce an appropriate returned value.

FUNCTION GetTemperatureBand(Temperature : REAL)
    RETURNS STRING

    IF Temperature < 10
    THEN
        RETURN "Cold"
    ELSE
        IF Temperature <= 24
        THEN
            RETURN "Moderate"
        ELSE
            RETURN "Warm"
        ENDIF
    ENDIF
ENDFUNCTION
Argument Path followed Returned value
6 First condition is true "Cold"
18 First false; second true "Moderate"
31 Both conditions false "Warm"

Executing RETURN immediately ends the current function call. Statements later in the same path are not executed.

Unreachable statement

FUNCTION GetCode() RETURNS CHAR
    RETURN 'A'
    OUTPUT "This statement cannot run"
ENDFUNCTION
Common mistake: placing necessary processing after RETURN. Once the return statement executes, control leaves the function.
Check every branch. A function should not reach ENDFUNCTION without producing the value promised by its interface.

Local Variables and the Return Boundary

A function may use local variables while calculating its result. These variables belong to the current function call and are not accessed directly by the main program.

FUNCTION CalculateArea(Width : REAL,
                       Height : REAL) RETURNS REAL
    DECLARE Area : REAL

    Area ← Width * Height

    RETURN Area
ENDFUNCTION

PanelArea ← CalculateArea(7.5, 4.2)
Identifier Location Role
Width Inside the function call Receives the first argument
Height Inside the function call Receives the second argument
Area Inside the function Stores the calculated local result
PanelArea Calling program Receives the returned value
Local variable: a variable available only within the subroutine in which it is declared.

A global variable has wider availability. Using global data unnecessarily can make a function harder to test because its result may depend on state that is not visible in its interface.

Common mistake: the main program cannot use Area directly. It receives the value through RETURN Area.

When Is a Function Appropriate?

Task Function appropriate? Reason
Calculate an area from two dimensions Yes The caller needs the calculated numeric result
Test whether a reading lies within a permitted range Yes A Boolean result can be used in a condition
Create a status label from a score Yes The function derives one string value
Find the largest of several supplied values Yes The function produces one selected value
Display a menu containing several output statements Usually a procedure The purpose is to perform an action rather than produce a value
Update several caller variables Usually a procedure The task does not naturally produce one direct result

Useful design question

Does the caller need one value that can replace the function call in an expression?
A strong justification names the value required by the caller: β€œA function is suitable because the algorithm needs one Boolean result that can be tested by the IF condition.”

Using Functions Efficiently

Do not repeat the same function call when its result can be stored and reused.

Repeated calculation

IF CalculateArea(Width, Height) > 50
THEN
    OUTPUT "Large area: ", CalculateArea(Width, Height)
ENDIF

The function may calculate the same area twice.

Improved version

Area ← CalculateArea(Width, Height)

IF Area > 50
THEN
    OUTPUT "Large area: ", Area
ENDIF

Keep dependencies visible

Hidden dependency

FUNCTION CalculateCharge() RETURNS REAL
    RETURN GlobalRate * GlobalDuration
ENDFUNCTION

Clearer interface

FUNCTION CalculateCharge(Rate : REAL,
                         Duration : REAL) RETURNS REAL
    RETURN Rate * Duration
ENDFUNCTION

Supplying the values through the interface makes the function easier to test with different data.

Common mistake: using a function mainly to change global variables. A function is normally clearer when its main purpose is to compute and return one result.

A Reliable Method for Tracing a Function

  1. Locate the function call inside the caller’s expression.
  2. Record the arguments supplied by the caller.
  3. Match each argument with the corresponding parameter.
  4. Enter the function and initialise its local state.
  5. Execute the body in order, including any selection or repetition.
  6. Identify the executed RETURN statement.
  7. Replace the original call with the returned value.
  8. Finish evaluating the caller’s expression.
  9. Continue with the next caller statement.

Suggested trace-table columns

Stage Caller expression Parameters Local variables Returned value Caller result
1 Record the expression containing the call Record received argument values Record function calculations Record the selected return value Complete the expression
Do not stop the trace at RETURN. Show how the caller uses the returned value.

Worked Example: Estimating Drone Endurance

A monitoring drone stores its battery capacity in watt-hours and its average power use in watts. One function calculates the estimated flight time, and a second function creates an endurance label.

Function definitions

FUNCTION CalculateFlightMinutes(CapacityWh : REAL,
                                AveragePowerW : REAL)
    RETURNS REAL

    DECLARE Hours : REAL
    DECLARE Minutes : REAL

    Hours ← CapacityWh / AveragePowerW
    Minutes ← Hours * 60

    RETURN Minutes
ENDFUNCTION

FUNCTION GetEnduranceBand(Minutes : REAL)
    RETURNS STRING

    IF Minutes < 15
    THEN
        RETURN "Short"
    ELSE
        IF Minutes <= 30
        THEN
            RETURN "Standard"
        ELSE
            RETURN "Extended"
        ENDIF
    ENDIF
ENDFUNCTION

Main program

DECLARE CapacityWh : REAL
DECLARE AveragePowerW : REAL
DECLARE FlightMinutes : REAL
DECLARE EnduranceBand : STRING

CapacityWh ← 72
AveragePowerW ← 180

FlightMinutes ← CalculateFlightMinutes(
                    CapacityWh,
                    AveragePowerW
                )

EnduranceBand ← GetEnduranceBand(FlightMinutes)

OUTPUT "Estimated flight time: ", FlightMinutes
OUTPUT "Endurance band: ", EnduranceBand

Trace the first function

Stage Result
Arguments 72 and 180
Parameters CapacityWh = 72, AveragePowerW = 180
Hours 72 / 180 = 0.4
Minutes 0.4 * 60 = 24
Returned value 24
Caller assignment FlightMinutes ← 24

Trace the second function

Test Result Action
24 < 15 FALSE Continue to the nested condition
24 <= 30 TRUE Return "Standard"
Caller assignment EnduranceBand ← "Standard"

Final output

Estimated flight time: 24
Endurance band: Standard
In a multi-function trace, complete the first call and store its returned value before tracing a later call that uses that result.

Interactive: Function Return Visualiser

Choose a scenario and trace the call, local processing, return statement and completed caller expression.

Calling program
BaseScore ← 14
FinalScore ← BaseScore + GetBonus()
OUTPUT FinalScore
BaseScore 14 FinalScore ?
Function
FUNCTION GetBonus() RETURNS INTEGER
    DECLARE Bonus : INTEGER
    Bonus ← 6
    RETURN Bonus
ENDFUNCTION
Function state Not entered Returned value Waiting
1. Function call Pause the caller and enter the function.
2. Function body Process parameters and local variables.
3. Return value Send one value back to the caller.
4. Caller continues Replace the call and complete the expression.
Step 1

Function call reached

The main program pauses evaluation when it reaches GetBonus().

BaseScore + GetBonus()
At the final step, read the displayed expression with the function call replaced by its returned value.

Common Mistakes and Misconceptions

  • Writing a function with no returned value: every reachable path should produce a result of the declared type.
  • Using CALL with a function: function calls belong within expressions.
  • Confusing RETURN and OUTPUT: one sends a value to the caller; the other displays data.
  • Omitting the return type: a function header must state the type of value produced.
  • Returning the wrong type: the returned value must match the declared return type.
  • Using a procedure inside an expression: a procedure does not directly produce a replacement value.
  • Trying to access a local variable from the caller: the function must return the required value.
  • Placing necessary statements after RETURN: they will not execute on that path.
  • Failing to return from one branch: a possible path may reach ENDFUNCTION without a result.
  • Evaluating the caller before the function: the call must be completed before the containing expression can finish.
  • Calling the same calculation repeatedly: store the result when it will be reused.
  • Depending unnecessarily on global variables: hidden dependencies make testing and tracing more difficult.

Practice

Question 1: identify the parts

FUNCTION GetLimit() RETURNS INTEGER
    RETURN 50
ENDFUNCTION

Identify the function header, function name, return type, return statement and end marker.

Question 2: write a simple function

Write a function called GetStartCode that returns the character 'S'.

Question 3: use a function call

Show how GetStartCode() could be used in an assignment to CurrentCode.

Question 4: trace replacement

FUNCTION GetIncrease() RETURNS INTEGER
    RETURN 7
ENDFUNCTION

Result ← 18 + GetIncrease()

Show the expression after replacement and state the final value of Result.

Question 5: function with parameters

Write a function called CalculatePerimeter that receives two integer dimensions and returns the perimeter of the rectangle.

Question 6: Boolean function

Write a function called IsValidPercentage that receives an integer and returns true only when it lies from 0 to 100 inclusive.

Question 7: procedure or function?

Choose and justify the more suitable subroutine:

  1. Display a five-line menu.
  2. Calculate the mean of two supplied numbers.
  3. Test whether a character is uppercase.
  4. Print a report heading and divider.

Question 8: find the type error

FUNCTION GetQuantity() RETURNS INTEGER
    RETURN "Twelve"
ENDFUNCTION

Explain and correct the error.

Question 9: find the unreachable statement

FUNCTION GetMessage() RETURNS STRING
    RETURN "Ready"
    OUTPUT "Function complete"
ENDFUNCTION

Explain why the output statement cannot execute.

Question 10: complete every return path

FUNCTION GetResult(Passed : BOOLEAN) RETURNS STRING
    IF Passed = TRUE
    THEN
        RETURN "Pass"
    ENDIF
ENDFUNCTION

Identify the missing path and rewrite the function.

Question 11: remove repeated calls

IF CalculateVolume(Length, Width, Height) > 100
THEN
    OUTPUT CalculateVolume(Length, Width, Height)
ENDIF

Rewrite the code so that the function is called once.

Question 12: nested function call

AreaCategory ← GetAreaCategory(
                   CalculateArea(8, 6)
               )

State which function call must be evaluated first and explain why.

Show suggested answers

Question 1

  • Header: FUNCTION GetLimit() RETURNS INTEGER
  • Name: GetLimit
  • Return type: INTEGER
  • Return statement: RETURN 50
  • End marker: ENDFUNCTION

Question 2

FUNCTION GetStartCode() RETURNS CHAR
    RETURN 'S'
ENDFUNCTION

Question 3

CurrentCode ← GetStartCode()

Question 4

Result ← 18 + 7
Result ← 25

Question 5

FUNCTION CalculatePerimeter(Length : INTEGER,
                            Width : INTEGER)
    RETURNS INTEGER

    RETURN 2 * (Length + Width)
ENDFUNCTION

Question 6

FUNCTION IsValidPercentage(Value : INTEGER)
    RETURNS BOOLEAN

    RETURN Value >= 0 AND Value <= 100
ENDFUNCTION

Question 7

  1. Procedure: the task displays several lines but does not need to produce a value for an expression.
  2. Function: the caller needs the calculated mean.
  3. Function: it can return a Boolean result for use in a condition.
  4. Procedure: its purpose is to perform output actions.

Question 8

The function promises an integer but returns a string. One correction is:

FUNCTION GetQuantity() RETURNS INTEGER
    RETURN 12
ENDFUNCTION

Question 9

Executing RETURN "Ready" ends the function call immediately, so the later output statement is unreachable.

Question 10

FUNCTION GetResult(Passed : BOOLEAN) RETURNS STRING
    IF Passed = TRUE
    THEN
        RETURN "Pass"
    ELSE
        RETURN "Not passed"
    ENDIF
ENDFUNCTION

Question 11

Volume ← CalculateVolume(Length, Width, Height)

IF Volume > 100
THEN
    OUTPUT Volume
ENDIF

Question 12

CalculateArea(8, 6) is evaluated first because its returned value becomes the argument supplied to GetAreaCategory.

Review

Concept Key idea
Function A named subroutine that returns one value
Function header Identifies the name, parameters and return type
Function interface Describes how the caller supplies data and receives a result
Return type The declared data type of the result
Return statement Sends a value to the caller and ends the function call
Function call Appears within an expression without the keyword CALL
Return replacement The returned value replaces the call before evaluation continues
Local variable Exists only within the subroutine where it is declared
Appropriate use The caller requires one calculated, selected or tested value
Final exam tip: trace the entire cycle: enter the function, process its local data, execute the correct return statement, replace the call with the returned value and finish the caller’s expression.