Define and use a procedure

11.3 Structured Programming – Define and Use a Procedure

Learning Objectives (AO1, AO2, AO3)

  • Define procedure and function and state when each should be used.
  • Write correct pseudocode for procedures and functions, including headers, parameters and return types.
  • Explain and illustrate the two parameter‑passing methods – call‑by‑value and call‑by‑reference – and predict their effect on original variables.
  • Distinguish procedures from functions with a quick decision‑tree/checklist.
  • Use built‑in/library routines and comment on the efficiency of a routine.
  • Design simple test cases for a procedure or function.

1. What Is a Procedure?

  • A named block of code that performs a specific task.
  • Can be called from any part of the program, promoting reuse and improving readability.
  • Does not return a value (or implicitly returns None in Python‑like languages).
  • Typical use: printing a report, writing to a file, updating a data structure.

2. What Is a Function?

  • A named block of code that returns a value to the caller.
  • Used when the result of a computation is needed later in the program.
  • Functions can be part of larger expressions (e.g., total = tax(price) + discount(price)).

3. Decision‑Tree – Procedure or Function?

Is a value required by the caller?

├─ Yes → Write a function (include a return statement)

└─ No → Write a procedure (no return needed)

Use this checklist during the Apply knowledge (AO2) part of the exam.

4. Common Elements of Procedures and Functions

ElementDescriptionTypical Python‑like Pseudocode
NameUnique identifier (lower‑case with underscores is recommended)def calculate_tax(...):
ParametersInput values supplied by the caller; may be passed by value or by reference(amount, rate)
BodyOne or more statements that perform the taskIndented block under the definition
Return valueOnly for functions; the value sent back to the callerreturn tax_amount (omitted for a pure procedure)

5. Parameter‑Passing Methods

MethodHow It WorksEffect on Original Variable
Call‑by‑valueThe argument’s value is copied into the parameter.Original variable is unchanged.
Call‑by‑referenceThe parameter becomes an alias for the argument variable.Changes to the parameter affect the original variable.

5.1 Example – Procedure Receiving a Value and a Reference

# Procedure that increments a number (value) and appends a tag to a list (reference)

def update_data(counter, tags):

counter = counter + 1 # call‑by‑value – does NOT change the caller's variable

tags.append('processed') # call‑by‑reference – modifies the original list

# No return statement – pure procedure

Calling code:

count = 5

my_tags = ['raw']

updatedata(count, mytags)

print(count) # → 5 (unchanged)

print(my_tags) # → ['raw', 'processed'] (modified)

5.2 Example – Swapping Two Variables (Call‑by‑Reference)

def swap(a, b): # both parameters are passed by reference

temp = a

a = b

b = temp

# No return needed – the caller's variables are now swapped

Calling code (pseudo‑language that supports reference parameters):

x = 12

y = 27

swap(x, y)

print(x, y) # → 27 12

In languages that only support call‑by‑value (e.g., Python), the same effect is achieved by returning the swapped values:

def swap_vals(a, b):

return b, a

x, y = swap_vals(x, y)

6. Syntax (Python‑like Pseudocode)

6.1 Procedure Header

def procedure_name(param1, param2, ...):

# body

statements

# (no return statement required)

6.2 Function Header

def function_name(param1, param2, ...):

# body

statements

return result

7. Calling a Procedure or Function

  • Procedure call (stand‑alone statement):

    procedure_name(arg1, arg2)

  • Function call (part of an expression):

    total = tax(price) + discount(price)

  • Built‑in/library routines are also functions, e.g.:

    length = len(my_list)   # built‑in function returns the size of the list

8. Illustrative Examples

8.1 Procedure – Print a Rectangle

def print_rectangle(width, height):

for i in range(height):

print('*' * width)

print_rectangle(5, 3)

8.2 Function – Maximum of Three Numbers

def maxofthree(a, b, c):

if a >= b and a >= c:

return a

elif b >= a and b >= c:

return b

else:

return c

largest = maxofthree(7, 12, 9)

print("Largest =", largest)

8.3 Function Used Inside an Expression

def tax(price):

return price * 0.20

def discount(price):

return price * 0.05

price = 100

total = price + tax(price) - discount(price) # total = 115.0

print("Total =", total)

8.4 Procedure vs. Function – Quick Comparison

  • Procedure: log_error(message) – writes a message to a file; no value needed.
  • Function: calculate_tax(amount) – returns the tax amount so it can be added to a total.

8.5 Function – Area of a Circle (Mathematical Formula)

def areaofcircle(radius):

pi = 3.14159

return pi * radius * radius # A = πr²

r = 5

circlearea = areaof_circle(r)

print("Area =", circle_area)

8.6 Procedure – Temperature Conversion (Prints Result)

def celsiustofahrenheit(c):

f = (9/5) * c + 32

print(c, "°C =", f, "°F")

celsiustofahrenheit(25)

9. Efficiency Tip (AO3)

  • Avoid unnecessary loops inside a routine. Prefer built‑in operations when they give the same result more quickly.
  • Example of an inefficient procedure and a refactored version:

    # Inefficient – uses a loop to sum a list

    def sum_list(nums):

    total = 0

    for i in range(len(nums)):

    total = total + nums[i]

    return total

    # Efficient – uses built‑in function

    def sum_list(nums):

    return sum(nums) # O(1) in Python, highly optimised

10. Naming Conventions & Interface Clarity (AO2)

  • Use lower‑case letters with underscores (e.g., calculate_tax).
  • Parameter names should be meaningful (price, rate).
  • If your language supports it, add optional type hints for readability:

    def calculate_tax(amount: float, rate: float) -> float:

    return amount * rate

11. Testing Procedures and Functions (AO3)

For each routine write at least one test case that shows the expected output.

11.1 Example Test Cases

# Test for maxofthree

assert maxofthree(3, 9, 5) == 9

# Test for print_rectangle (visual – check output manually)

print_rectangle(4, 2)

# Expected output:

#

#

12. Common Pitfalls and How to Avoid Them

  • Wrong number or type of arguments – always check the routine’s signature before calling.
  • Unintended modification of arguments – use call‑by‑value for data that must stay unchanged; use call‑by‑reference only when you deliberately want to modify the caller’s variable.
  • Procedures that are too large or do unrelated tasks – aim for a single, well‑defined purpose (single‑responsibility principle).
  • Missing return in a function or adding one in a pure procedure – keep the distinction clear.
  • Ignoring built‑in/library functions – they are often more efficient and reduce the chance of errors.

13. Practice Questions (Exam‑Style)

  1. Write a procedure printmaxof_three(a, b, c) that prints the greatest of three numbers (no return value).
  2. Explain the difference between call‑by‑value and call‑by‑reference using a short pseudocode example that modifies a list.
  3. Given the following code, what is printed and why?

    def increment(x):

    x = x + 1

    return x

    num = 10

    increment(num)

    print(num)


    Answer: 10 is printed because num is passed by value; the incremented value is returned but not stored.

  4. Design a function celsiustofahrenheit(c) that returns the Fahrenheit temperature. Include the formula \(F = \frac{9}{5}C + 32\) in your answer.
  5. Identify a situation in a simple banking program where a procedure would be more appropriate than a function, and justify your choice.
  6. Refactor the following inefficient procedure to improve its efficiency:

    def duplicate_chars(text):

    result = ''

    for i in range(len(text)):

    result = result + text[i] + text[i]

    return result


    Provide a more efficient version using a built‑in operation.

Suggested flowchart: Define → Pass parameters (value/reference) → Execute body → (optional) return result → Continue program.