Define and use a function

11.3 Structured Programming – Define and Use a Function

Objective

Students will be able to define a function (or procedure) and invoke it correctly using the Cambridge‑approved pseudocode format, and understand how this fits into the wider AS‑ and A‑Level Computer Science syllabus.

Syllabus Context

This topic belongs to the Programming – Functions and Procedures sub‑section of the Cambridge International AS & A Level Computer Science (9618) syllabus. Mastery of functions underpins many other syllabus blocks, for example:

  • Algorithm design and data structures (blocks 15‑16)
  • Recursion and exception handling (A‑Level block 18)
  • File handling and user‑defined data types (A‑Level block 13‑14)
  • Practical programming in Paper 4 (Java, Python, Visual Basic)

Key Concepts

  • Function (or Procedure) – A self‑contained block of code that performs a specific task.
  • Function name – Identifier used to call the routine.
  • Parameter list – Variables that receive values (arguments) from the caller.
  • Return value – Data sent back to the caller (optional for a procedure).
  • Scope – Region of the program where a variable is accessible; parameters and variables defined inside a function are local.
  • Passing method – The way arguments are transferred (pass‑by‑value or pass‑by‑reference). Choosing the correct method is part of AO2 – analyse the problem and decide on an appropriate solution.

Cambridge Pseudocode Syntax

Function (returns a value)

FUNCTION function_name (parameter1, parameter2, …) RETURNS return_type
    // body of the function
    …
    RETURN result
END FUNCTION

Procedure (does not return a value)

PROCEDURE procedure_name (parameter1, parameter2, …)
    // body of the procedure
    …
END PROCEDURE

Steps to Define and Use a Function

  1. Choose a clear, descriptive function name.
  2. Identify the input parameters required and decide on the passing method (value or reference).
  3. Write the function body that carries out the required operations.
  4. If a result is required, include a RETURN statement; otherwise define a procedure.
  5. Place the definition before any CALL statement (or use a forward declaration where the language permits).
  6. Invoke the function or procedure from the main program (or another routine) using a CALL statement and supply appropriate arguments.

Example – Function to Calculate the Area of a Circle

Mathematical formula: \(A = \pi r^{2}\)

FUNCTION CircleArea (radius) RETURNS REAL
    CONSTANT pi = 3.14159
    SET area = pi * radius * radius
    RETURN area
END FUNCTION

// ---- Main program ----
SET r = 5
SET a = CircleArea(r)
OUTPUT "Area = ", a

Calling (Invoking) a Function

A call can appear anywhere a value is needed, for example in an assignment, an OUTPUT statement, or as an argument to another function.

SET result = FunctionName(arg1, arg2)   // value returned is stored in result
CALL ProcedureName(arg1, arg2)         // no value returned
OUTPUT FunctionName(10)                // value printed directly

Parameter Passing Methods

Method Description Effect on Original Variable
Pass‑by‑value A copy of the argument is passed to the routine. The original variable in the caller remains unchanged.
Pass‑by‑reference The address of the argument is passed. Changes made inside the routine affect the original variable.

Note: Selecting the correct passing method is part of AO2 – analyse the problem and decide on an appropriate solution.

Procedures vs. Functions

  • Function: Returns a value using RETURN. Example: CircleArea above.
  • Procedure: Performs actions but does not return a value.
    PROCEDURE DisplayGreeting (name)
        OUTPUT "Hello, ", name, "!"
    END PROCEDURE
            

Common Errors and How to Avoid Them

  • Missing RETURN statement – If the caller expects a value but the routine omits RETURN, the result is undefined.
  • Incorrect number of arguments – Ensure the call supplies exactly the parameters listed in the header.
  • Variable name clashes (shadowing) – Use distinct names for parameters and global variables, or qualify globals explicitly.
  • Infinite recursion – Every recursive routine must have a clear base case that stops further calls.
  • Wrong passing method – Choose pass‑by‑value when the original data must stay unchanged; choose pass‑by‑reference when the routine needs to modify the caller’s data.

Assessment Objective (AO) Mapping

AO1 – Knowledge and Understanding: terminology (function, procedure, parameter, scope, return value).

AO2 – Application of Knowledge: selecting the correct passing method, deciding between a function and a procedure, organising code into reusable blocks.

AO3 – Analysis and Design: writing correct pseudocode, tracing the flow of arguments and return values, debugging common errors.

Practical Component (Paper 4) – Quick Checklist

  • All functions/procedures must be defined before they are called (or declared as forward where the language allows).
  • Only the standard libraries for console I/O are permitted (e.g., System.out.println in Java).
  • No global variables unless explicitly required by the question.
  • Remember to include a return statement for every function that the question expects to produce a value.
  • Test edge cases (e.g., zero or negative values) to avoid runtime errors.

Integration with the Wider Syllabus

Syllabus Block Key Content Link to Functions
1 Information Representation – Data Representation Binary, hexadecimal, character encoding, floating‑point. Functions are used to convert between representations (e.g., BinaryToDecimal).
2 Communication – Networks OSI model, protocols, network topologies. Procedures model sending/receiving packets (e.g., SendPacket).
3 Hardware – CPU Architecture & Assembly Registers, instruction set, simple assembly language. Sub‑routines in assembly correspond to functions in pseudocode.
4 Operating Systems Processes, scheduling, memory management. Functions illustrate modular design of OS services (e.g., AllocateMemory).
5 Security & Ethics Encryption, authentication, legal/ethical issues. Procedures can encapsulate encryption algorithms (EncryptMessage).
6 Databases Data models, SQL, normalisation. Functions return query results; procedures perform updates.
7 Algorithm Design & Data Structures Sorting, searching, linked lists, trees. Recursive functions (e.g., BinarySearch) are essential.
8 Software Development Life‑Cycle Planning, design, implementation, testing, maintenance. Modular functions support testing and maintenance.
A‑Level 13 User‑Defined Data Types Records/structures, arrays of records. Functions can accept and return complex types (e.g., StudentRecord).
A‑Level 14 File Organisation Sequential, random, indexed files. Procedures handle file I/O (e.g., ReadRecord).
A‑Level 15 Floating‑Point Representation IEEE 754, rounding errors. Functions perform precise arithmetic and rounding.
A‑Level 16 Network Protocols TCP/IP, HTTP, security protocols. Procedures model protocol handshakes.
A‑Level 17 Parallel Processing Threads, synchronization. Functions can be executed as concurrent tasks.
A‑Level 18 Recursion & Exception Handling Base cases, stack overflow, try‑catch. Recursive functions are a core example; procedures may raise exceptions.
A‑Level 19 Virtual Machines & Interpreters Bytecode, garbage collection. Function calls map to VM stack frames.
A‑Level 20 Further Programming Paradigms Object‑oriented concepts, event‑driven programming. Methods in OOP are specialised functions with implicit this parameter.

Practice Questions

  1. Write a FUNCTION MaxOfThree (a, b, c) RETURNS REAL that returns the greatest of three numbers. Include a RETURN statement and use appropriate conditional logic.
  2. Explain the difference between a function that returns a value and a procedure that does not. Provide a short example of each (different from the ones above).
  3. Given the routine below, state what is printed on each line and why:
    FUNCTION AddOne (x) RETURNS INTEGER
        SET x = x + 1
        RETURN x
    END FUNCTION
    
    SET y = 5
    OUTPUT AddOne(y)   // line A
    OUTPUT y           // line B
            
    • Line A prints 6 – the value returned by the function.
    • Line B prints 5y was passed by value, so the original variable is unchanged.
  4. Design a PROCEDURE SwapValues (a, b) that exchanges the contents of two integer variables using pass‑by‑reference. Show a short test in the main program that demonstrates the swap.

Summary Table

Aspect Definition (syllabus terminology) Typical Cambridge Pseudocode
Function name Identifier used to call the routine FUNCTION name ( … )
Procedure name Identifier for a routine that does not return a value PROCEDURE name ( … )
Parameters Variables listed in the header that receive arguments (param1, param2, …)
Return value Data sent back to the caller RETURN expression
Calling a routine Executing the routine with specific arguments result = FunctionName(arg1, arg2) or CALL ProcedureName(arg1, arg2)
Scope Region of the program where a variable is accessible Local variables exist only inside the routine body; globals are declared outside.
Passing method How arguments are transferred (value vs. reference) Decided in the design stage; affects whether the original variable can be modified.
Suggested diagram: Flowchart showing (1) Function header, (2) Parameter passing, (3) Execution of the body, (4) Return of a value (or end of procedure). This visual reinforces the sequence required by the syllabus.

Create an account or Login to take a Quiz

102 views
0 improvement suggestions

Log in to suggest improvements to this note.