Explain where in the construction of an algorithm it is appropriate to use a function

11.3 Structured Programming – Using Functions

Learning Objective

Explain at which stage in the construction of an algorithm it is appropriate to introduce a function, and justify how doing so improves the design, implementation, testing and maintenance of a program.

Syllabus Alignment (Cambridge International AS & A Level Computer Science 9618)

Specification SectionRelevant Content
11.3 Using FunctionsDefine, call, test functions; use parameters and return values.
11.2 ConstructsShow that functions can contain IF…ELSE, CASE, and loop structures.
11.1 Programming BasicsVariable/constant declaration, input‑output and scope rules for functions.
12.1 Program Development Life‑cycleRelate “function‑first” design to analysis, design, coding, testing and maintenance.
12.3 Program Testing and MaintenanceUnit‑test individual functions before integration.
Assessment Objectives

  • AO1 – Knowledge of terminology and concepts (e.g., encapsulation, parameterisation).
  • AO2 – Application of knowledge to solve problems (selecting and writing appropriate functions).
  • AO3 – Design and analysis of solutions (justifying the placement of functions in the algorithm).

Why Use Functions? (Benefits)

  • Encapsulation – isolates a specific task and hides implementation details.
  • Re‑use – the same code can be called from many places without duplication.
  • Readability – the main algorithm reads like a high‑level description of the problem.
  • Testability – each function can be unit‑tested independently (AO3).
  • Maintainability – a change to a task is made in one location only, reducing the risk of new errors.

When to Introduce a Function (Decision Checklist)

  1. Repeated Action: identical step‑sequences appear two or more times.
  2. Complex Sub‑task: a portion of the algorithm involves several steps and is conceptually distinct.
  3. Abstraction Needed: hiding internal steps makes the main flow clearer.
  4. Parameterisation: the same logic must operate on different data values.
  5. Testing Requirement: the sub‑task should be verified in isolation before integration.

Typical Points in the Development Process to Insert Functions

Stage of DevelopmentWhat to DoWhy a Function Helps
Problem AnalysisIdentify distinct operations (e.g., “calculate average”, “sort list”).Creates a clear mapping from the problem description to program modules.
Algorithm Design (pseudocode)Replace repeated step sequences with a named sub‑algorithm.Reduces pseudocode length and highlights logical structure.
Implementation (coding)Write the function definition before the main routine (or in a separate module).Ensures the main routine reads like a high‑level plan and respects scope rules.
Testing & DebuggingUnit‑test each function independently, then integrate.Isolates faults and speeds up verification (AO3).
MaintenanceModify a function when the underlying task changes.Only one location needs updating, reducing the risk of new errors.

Cambridge‑Style Pseudocode Conventions for Functions

ElementSyntax
Function headerFUNCTION name(parameter‑list) → return‑type
ParametersComma‑separated, each with a type (e.g., list: LIST OF INTEGER)
Return statementRETURN expression
End of functionEND FUNCTION

Simple Example

FUNCTION max(a: INTEGER, b: INTEGER) → INTEGER

IF a > b THEN

RETURN a

ELSE

RETURN b

END IF

END FUNCTION

Scope, Declaration and Parameter Passing

  • Local variables are declared inside a function and cease to exist when the function returns.
  • Global variables / constants are declared outside any function; they are accessible to all functions unless shadowed.
  • Parameters are passed by value unless the syllabus explicitly allows reference passing. The called function receives a copy, so changes to the parameter do not affect the original variable.

Function with Multiple Parameters and a Return Value

FUNCTION swapIfGreater(x: INTEGER, y: INTEGER) → LIST OF INTEGER

IF x > y THEN

RETURN [y, x] // returns a list with the values swapped

ELSE

RETURN [x, y]

END IF

END FUNCTION

Interaction with Control Structures

A function may contain any standard construct (IF, CASE, FOR, WHILE). Conversely, a function can be called from within those constructs.

FUNCTION isPrime(n: INTEGER) → BOOLEAN

IF n < 2 THEN RETURN FALSE END IF

FOR i FROM 2 TO FLOOR(SQRT(n))

IF n MOD i = 0 THEN RETURN FALSE END IF

END FOR

RETURN TRUE

END FUNCTION

FOR i FROM 1 TO 20

IF isPrime(i) THEN OUTPUT i, " is prime" END IF

END FOR

Worked Example – Computing the Median of a List

Problem statement: For each data set read from input, output its median. The steps “sort the list” and “pick the middle element” are repeated for every set.

Version A – No functions (pseudocode)

READ sets

FOR s FROM 1 TO sets

READ size

READ size numbers INTO list

// bubble sort

FOR i FROM 1 TO size-1

FOR j FROM i+1 TO size

IF list[i] > list[j] THEN SWAP list[i], list[j] END IF

END FOR

END FOR

// pick median

IF size MOD 2 = 1 THEN

median ← list[(size+1)/2]

ELSE

median ← (list[size/2] + list[size/2+1]) / 2

END IF

OUTPUT median

END FOR

Version B – With functions (Cambridge‑style pseudocode)

FUNCTION sortAscending(data: LIST OF INTEGER) → LIST OF INTEGER

FOR i FROM 1 TO LENGTH(data)-1

FOR j FROM i+1 TO LENGTH(data)

IF data[i] > data[j] THEN SWAP data[i], data[j] END IF

END FOR

END FOR

RETURN data

END FUNCTION

FUNCTION median(data: LIST OF INTEGER) → REAL

SET sorted ← sortAscending(data)

SET n ← LENGTH(sorted)

IF n MOD 2 = 1 THEN

RETURN sorted[(n+1)/2]

ELSE

RETURN (sorted[n/2] + sorted[n/2+1]) / 2

END IF

END FUNCTION

// Main program

READ sets

FOR s FROM 1 TO sets

READ size

READ size numbers INTO numbers

OUTPUT median(numbers)

END FOR

Benefits observed

  • The main loop now mirrors the problem description – “read data, output median”.
  • Sorting and median extraction are each isolated, making them easy to test.
  • If a more efficient sorting algorithm is later required, only sortAscending needs to be changed.

Testing Functions (Unit Testing)

  1. Write a set of test cases for each function before integrating it.
  2. For sortAscending, test:

    • An already‑sorted list.
    • A reverse‑sorted list.
    • A list containing duplicate values.

  3. For median, test:

    • Odd‑length lists (e.g., [3,1,4] → 3).
    • Even‑length lists (e.g., [2,8,5,7] → 6.0).
    • Lists with negative numbers and zeros.

  4. Record expected vs. actual output; any discrepancy indicates a fault to be fixed before the main program runs.

Assessment Objective (AO) Mapping for This Topic

AOWhat the student must demonstrate
AO1Define “function”, “parameter”, “return value”, “scope”, and explain the benefits of encapsulation.
AO2Apply the decision checklist to select appropriate points in an algorithm to introduce a function; write correct Cambridge‑style pseudocode.
AO3Design a solution that uses functions to improve readability, re‑use and testability; justify the placement of each function within the development life‑cycle.

Practical Implementation Tips (Paper 4 – Programming)

  • Choose a language you are comfortable with (Java, Python, Visual Basic). All three support functions/sub‑routines and map cleanly onto Cambridge pseudocode.
  • Follow the language‑specific syntax for:

    • Function header (e.g., public static int max(int a, int b) in Java).
    • Parameter passing – most exam languages use pass‑by‑value for primitives and pass‑by‑reference for objects/arrays.
    • Returning a value – use return and ensure the declared return type matches.

  • Remember to keep the main routine short; it should orchestrate calls to your functions, not contain detailed logic.
  • When testing on the exam computer, write a small “driver” program that calls each function with known inputs and prints the results – this satisfies the unit‑testing requirement.

A‑Level Extension Topics (Relevant to Functions)

  • Recursion (20.2) – functions that call themselves (e.g., factorial, binary‑search).
  • Exception handling (20.2) – using TRY…CATCH inside functions to manage run‑time errors.
  • Abstract Data Types (19.2) – designing functions that operate on custom structures such as stacks, queues or linked lists.
  • Algorithmic efficiency (14.2) – comparing sorting functions (bubble vs. insertion vs. merge) and discussing Big‑O notation.
  • Database access (21.2) – encapsulating SQL queries inside functions for modular data retrieval.

Suggested Diagram

Flowchart illustrating the hierarchical call structure: Main program → mediansortAscending. Each block is labelled with its function name to visualise encapsulation.

Key Take‑aways

  • Introduce a function during the design stage when a task can be identified as a distinct, reusable unit.
  • Use functions to replace repeated code, hide complexity, and enable independent testing.
  • Follow Cambridge pseudocode conventions: clear header, parameter list, return statement, proper indentation.
  • Observe scope rules – variables declared inside a function are local; parameters are passed by value unless otherwise specified.
  • Unit‑test each function before integrating it into the main program to satisfy AO3 requirements.