SLIDE 1
CSZone.co.uk
Click to reveal · Arrow keys also work
OCR J277 · Component 2 · Topic 2.2.1f

Programming Techniques
Subroutines

Procedures, functions, parameters, return values and local variables — OCR ERL and Python

CSZone OCR GCSE Computer Science J277
Learning Objectives

By the end of this video you will be able to...

Explain what a subroutine is and state the benefits of using subroutines in a program
Define and call a procedure in OCR ERL — a named block of code that carries out a task with no return value
Define and call a function in OCR ERL — a subroutine that uses RETURN to send a value back to the caller
Use parameters to pass data into subroutines, and distinguish parameters from arguments
Explain local variables — why they only exist inside their subroutine — and write equivalent subroutines in Python using def
⚡ Subroutines are the foundation of structured, maintainable programs. Every large program is built from small, named, reusable blocks of code.
Subroutines

What is a subroutine — and why use one?

DEFINITION
A subroutine is a named block of code designed to perform a specific task. It is defined once, then called (executed) by name from anywhere in the program — as many times as needed. There are two types: procedures and functions.
WITHOUT SUBROUTINES — REPEATED CODE
// Greet user at login: print("===============") print("Welcome, Alice!") print("===============") // ... 50 lines later, greet again: print("===============") print("Welcome back!") print("===============")
WITH SUBROUTINES — DEFINE ONCE, CALL ANYWHERE
PROCEDURE printBanner(msg) print("===============") print(msg) print("===============") ENDPROCEDURE printBanner("Welcome, Alice!") // ... anywhere else: printBanner("Welcome back!")
BENEFITS OF SUBROUTINES — EXAM POINTS
Reuse — write the code once, call it many times. No duplication
Maintainability — fix a bug in one place; the fix applies everywhere the subroutine is called
Easier testing — each subroutine can be tested in isolation
Readability — meaningful subroutine names make code self-documenting
Abstraction — the caller doesn't need to know how the subroutine works internally, only what it does
TWO TYPES
Procedure — carries out a task. Does not return a value.
Function — calculates and returns a value to the caller.
Procedures

Defining and calling a procedure

PROCEDURE
A procedure is a named block of code that performs a task. It does not return a value. Use PROCEDURE and ENDPROCEDURE to define it.
OCR ERL — PROCEDURE ANATOMY
PROCEDURE greet(name) KEYWORD NAME PARAMETER print("Hello, " + name) BODY print("Welcome!") ENDPROCEDURE END KEYWORD
CALLING A PROCEDURE
// Call with argument "Alice": greet("Alice") ← prints: Hello, Alice ← Welcome! // Call again with a different argument: greet("Bob") ← prints: Hello, Bob ← Welcome!
PROCEDURE — NO PARAMETERS
// Procedures can have no parameters: PROCEDURE printDivider() print("========================") ENDPROCEDURE printDivider() ← call with no arguments print("Main Menu") printDivider() ← call it again
MULTIPLE PARAMETERS
PROCEDURE showScore(name, score) print(name + ": " + str(score)) ENDPROCEDURE showScore("Alice", 95) ← prints: Alice: 95
KEY RULE
A procedure does not use RETURN. It just executes its body and control passes back to the caller when ENDPROCEDURE is reached. If a question asks you to return a value, you need a function, not a procedure.
Functions

Defining and calling a function

FUNCTION
A function is a subroutine that returns a value to the caller using the RETURN keyword. Use FUNCTION and ENDFUNCTION.
OCR ERL — FUNCTION ANATOMY
FUNCTION add(a, b) KEYWORD NAME PARAMS resulta + b BODY RETURN result RETURN VALUE ENDFUNCTION END KEYWORD
CALLING A FUNCTION — CAPTURE THE RETURN VALUE
// The function returns a value — store it: totaladd(3, 4) print(total) ← 7 // Or use the call directly in an expression: print(add(10, 20)) ← 30 IF add(5, 5) == 10 THEN print("Correct!") ENDIF
FUNCTION — AREA CALCULATOR EXAMPLE
FUNCTION calculateArea(width, height) RETURN width * height ENDFUNCTION areacalculateArea(5, 3) print("Area: " + str(area)) ← Area: 15
FUNCTION — WITH A CONDITION
FUNCTION isEven(n) IF n MOD 2 == 0 THEN RETURN TRUE ELSE RETURN FALSE ENDIF ENDFUNCTION print(isEven(6)) ← TRUE print(isEven(7)) ← FALSE
RETURN immediately ends the function and sends the value back. Any code after RETURN in that branch does not run. A function must have at least one RETURN statement.
Parameters

Parameters and arguments — the difference

PARAMETER
The placeholder name in the subroutine definition. It receives the value when the subroutine is called.
ARGUMENT
The actual value passed in when the subroutine is called. It is assigned to the parameter.
FUNCTION square(n) n = PARAMETER RETURN n * n ENDFUNCTION resultsquare(7) 7 = ARGUMENT
HOW ARGUMENTS MAP TO PARAMETERS
PROCEDURE display(label, value) print(label + ": " + str(value)) ENDPROCEDURE display("Score", 88) ← label = "Score", value = 88 ← prints: Score: 88
ARGUMENTS ARE PASSED IN ORDER
FUNCTION power(base, exp) result1 FOR i = 1 TO exp resultresult * base NEXT i RETURN result ENDFUNCTION print(power(2, 3)) ← base=2, exp=3 → 8 print(power(3, 2)) ← base=3, exp=2 → 9
ORDER MATTERS
Arguments are matched to parameters left to right by position. power(2, 3) ≠ power(3, 2) — the order you pass arguments in determines which parameter receives which value.
MEMORY AID
Parameter = Placeholder (in the Programme / definition). Argument = Actual value (At the call site). Parameters are defined once; arguments change every time you call.
Local Variables

Local variables — scope inside a subroutine

LOCAL VARIABLE
A local variable is one declared inside a subroutine. It only exists while that subroutine is running. When the subroutine ends, the local variable is destroyed. It cannot be accessed from outside the subroutine.
FUNCTION calculateTax(price) rate0.2 LOCAL taxprice * rate LOCAL RETURN tax ENDFUNCTION resultcalculateTax(100) // 'rate' and 'tax' do NOT exist here print(result) ← 20.0
PARAMETERS ARE ALSO LOCAL
Parameters like price above are also local to the subroutine. They are created when the subroutine is called and destroyed when it ends. They cannot be accessed outside.
TWO SUBROUTINES — SAME VARIABLE NAME, NO CONFLICT
FUNCTION double(x) resultx * 2 ← local to double() RETURN result ENDFUNCTION FUNCTION triple(x) resultx * 3 ← local to triple() RETURN result ENDFUNCTION // Both use 'result' — no conflict! print(double(5)) ← 10 print(triple(5)) ← 15
BENEFITS OF LOCAL VARIABLES
No naming conflicts — two subroutines can use the same variable name without clashing
Self-contained — subroutines don't accidentally affect other parts of the program
Easier to test — each subroutine only relies on its own parameters and locals
Python

Subroutines in Python — the def keyword

Python uses def for BOTH procedures and functions
In Python, both procedures and functions are defined using the def keyword. There is no separate PROCEDURE keyword. A Python function with no return statement acts as a procedure.
PYTHON — PROCEDURE (no return)
def greet(name): print("Hello, " + name) print("Welcome!") greet("Alice") # Hello, Alice # Welcome!
PYTHON — FUNCTION (with return)
def add(a, b): return a + b total = add(3, 4) print(total) # 7
OCR ERL vs PYTHON — SIDE BY SIDE
FeatureOCR ERLPython
Procedure startPROCEDURE name()def name():
Procedure endENDPROCEDURE(dedent / blank line)
Function startFUNCTION name()def name():
Function endENDFUNCTION(dedent / blank line)
Return valueRETURN valuereturn value
PYTHON — FULL EXAMPLE
def calculateArea(width, height): return width * height def showResult(label, value): print(label + ": " + str(value)) area = calculateArea(5, 3) showResult("Area", area) # Area: 15
Subroutines

How subroutine calls and return values work

EXECUTION FLOW — PROCEDURE CALL
PROCEDURE greet(name) print("Hi, " + name) ENDPROCEDURE print("Before call") ← runs first greet("Alice") ← jumps into procedure print("After call") ← runs after ENDPROCEDURE
OUTPUT ORDER
1"Before call"
2"Hi, Alice" (inside procedure)
3"After call"
When a subroutine is called, execution jumps to the subroutine body. When ENDPROCEDURE or RETURN is reached, execution returns to the line after the call.
EXECUTION FLOW — FUNCTION CALL WITH RETURN
FUNCTION double(x) RETURN x * 2 ← sends value back ENDFUNCTION print("Start") ansdouble(5) ← 10 stored in ans print(ans) ← 10 print("Done")
OUTPUT ORDER
1"Start"
2double(5) called → RETURN 10
310 (ans = 10, then printed)
4"Done"
REMEMBER
To use a function's return value, you must either store it in a variable (ans ← double(5)) or use the call directly in an expression (print(double(5))). If you just write double(5) alone, the return value is lost.
Worked Example

Subroutines — combining a procedure and function

PROBLEM
Write a program that uses: (1) a function to calculate the average of three scores, and (2) a procedure to display the result with a label. Then call both to process two sets of scores.
OCR ERL SOLUTION
FUNCTION average(a, b, c) RETURN (a + b + c) / 3 ENDFUNCTION PROCEDURE showAverage(name, avg) print(name + " average: " + str(avg)) ENDPROCEDURE avg1average(70, 85, 90) showAverage("Alice", avg1) avg2average(60, 75, 80) showAverage("Bob", avg2)
PYTHON SOLUTION
def average(a, b, c): return (a + b + c) / 3 def showAverage(name, avg): print(name + " average: " + str(avg)) avg1 = average(70, 85, 90) showAverage("Alice", avg1) avg2 = average(60, 75, 80) showAverage("Bob", avg2)
WHAT THIS EXAMPLE SHOWS
average() is a function — it calculates and returns a value using RETURN
showAverage() is a procedure — it outputs but returns nothing
Both are called twice with different arguments — code is reused, not duplicated
Local variables — a, b, c inside average() don't exist in the main program
Exam Practice

Subroutines — exam questions

Question 1 — 1 mark
State one difference between a procedure and a function.
Answer — Q1
A function returns a value to the caller using RETURN; a procedure does not return a value. (1 mark — any one valid difference)
Also accepted: "A procedure is called on its own line; a function call can be used in an expression or assigned to a variable."
Question 2 — 2 marks
Write OCR ERL to define a procedure called printLine that takes a parameter called msg and outputs it. Then call it with the argument "Hello".
Answer — Q2
PROCEDURE printLine(msg) ← [1] print(msg) ENDPROCEDURE printLine("Hello") ← [1]
Mark 1: correct PROCEDURE definition with parameter. Mark 2: correct call with "Hello" as argument.
Question 3 — 4 marks
Write OCR ERL pseudocode for a function called calculateArea that:
• takes two parameters: width and height
• calculates and returns their product
• is then called with values 6 and 4, with the result stored in a variable called area and output
Exam Answers

Question 3 — answer and mark scheme

Q3 MARK SCHEME
FUNCTION calculateArea(width, height) ← [1] RETURN width * height ← [1] ENDFUNCTION areacalculateArea(6, 4) ← [1] print(area) ← [1]
Mark 1: FUNCTION keyword, correct name, two parameters.
Mark 2: RETURN with correct calculation (width * height).
Mark 3: function called with arguments 6 and 4, result stored.
Mark 4: result printed / output correctly.
COMMON MARK LOSSES ON THIS Q
• Using PROCEDURE instead of FUNCTION — the question asks for a return value, which requires FUNCTION
• Forgetting RETURN — defining the function but not returning the product
• Not storing the result: writing calculateArea(6,4) alone without assigning it
PYTHON EQUIVALENT
def calculateArea(width, height): return width * height area = calculateArea(6, 4) print(area) # 24
PROCEDURE vs FUNCTION — DECISION GUIDE
If the task says...Use...
"output / display / print"PROCEDURE
"calculate and return"FUNCTION
"return a value"FUNCTION
"store the result of calling..."FUNCTION
⚡ In a 4-mark subroutine question: mark 1 = correct keyword + name + parameters. Mark 2 = correct body logic. Mark 3 = RETURN (for functions) or correct call. Mark 4 = result used / output correctly. Plan these four beats before you write.
Common Mistakes

Common mistakes — avoid these in the exam

MISTAKE 1 — Using PROCEDURE when a return value is needed
Writing PROCEDURE calculateArea(...) but then trying to use a RETURN statement or store the result. PROCEDUREs do not return values — if the question requires a return value, it must be a FUNCTION
✓ If the question says "return", "calculate and send back", or stores the result — use FUNCTION and ENDFUNCTION
MISTAKE 2 — Forgetting RETURN in a function
Defining a FUNCTION, performing a calculation inside it, but never writing RETURN. Without RETURN, the function completes but sends nothing back — the caller receives nothing, and the result is lost
✓ Every FUNCTION must have at least one RETURN value statement before ENDFUNCTION
MISTAKE 3 — Not storing the return value
Calling a function but not capturing what it returns: writing calculateArea(5, 3) on its own. The function runs, RETURN sends 15 back — but nothing stores it, so it is immediately lost
✓ Store it: area ← calculateArea(5, 3) or use directly: print(calculateArea(5, 3))
MISTAKE 4 — Confusing parameters and arguments
Saying "arguments are in the definition" or "parameters are passed when calling" — these are the wrong way round. This distinction appears directly in exam questions about subroutines
Parameters are in the definition (placeholders). Arguments are the actual values passed at the call site
Summary

Key points — 2.2.1f

A subroutine is a named block of code defined once and called by name anywhere in the program. Benefits: code reuse, maintainability, easier testing, readability, and abstraction
A procedure performs a task but does not return a value. Define with PROCEDURE name(params) and ENDPROCEDURE. Call it by name on its own line
A function calculates and returns a value using RETURN. Define with FUNCTION name(params) and ENDFUNCTION. Capture the return value when calling
Parameters are the placeholder names in the definition. Arguments are the actual values passed when calling. They map left to right in order. Variables inside a subroutine are local — they do not exist outside it
In Python, both procedures and functions use def. A function uses return; a procedure-style function has no return statement. Python's def replaces both PROCEDURE and FUNCTION
⚡ Next topic: 2.3.1 — Defensive Design. Input validation, anticipating misuse, and writing robust programs.
2.2.1f Complete

Subroutines
Procedures · Functions · Parameters

Get the full resource pack at CSZone.co.uk

📄
Marked Worksheet
CSZone.co.uk
Quiz
CSZone.co.uk
📊
Slides
CSZone.co.uk
Next Up
2.3.1 — Defensive Design