Procedures & Functions (Cambridge (CIE) IGCSE Computer Science): Revision Note

Exam code: 0478 & 0984

Robert Hampton

Written by: Robert Hampton

Reviewed by: James Woodhouse

Updated on

What are functions and procedures?

  • Functions and procedures are a type of sub program, a sequence of instructions that perform a specific task or set of tasks

  • Procedures and functions are defined at the start of the code

  • Sub programs are often used to simplify a program by breaking it into smaller, more manageable parts

  • Sub programs can be used to:

    • Avoid duplicating code and can be reused throughout a program

    • Improve the readability and maintainability of code

    • Perform calculations, to retrieve data, or to make decisions based on input

  • Parameters are values that are passed into a sub program

    • Parameters can be variables or values and they are located in brackets after the name of the sub program

    • Example: FUNCTION TaxCalculator(pay,taxcode) OR PROCEDURE TaxCalculator(pay,taxcode)

  • Sub programs may have up to three parameters

  • To use a sub program you 'call' it from the main program

What's the difference between a function and procedure?

  • A Function returns a value whereas a procedure does not

Procedures

  • Procedures are defined using the PROCEDURE keyword in pseudocode or def keyword in Python

  • A procedure can be written as:


    PROCEDURE <identifier>
    <statements>
    ENDPROCEDURE

  • Or if parameters are being used:

    PROCEDURE <identifier>(<param1>:<data type>, <param2>:<data type>...)
    <statements>
    ENDPROCEDURE

Creating a procedure

Pseudocode

PROCEDURE CalculateArea(Length : INTEGER, Width : INTEGER)
    DECLARE Area : INTEGER
    Area ← Length * Width
    OUTPUT "The area is ", Area
ENDPROCEDURE

Python

def ageCheck(age):
    if age > 18:
        print("You are old enough")
    else:
        print("You are too young")
  • To call a procedure, it can be written as:


    CALL <identifier>
    CALL <identifier>(Value1,Value2...)

Calling a procedure

Pseudocode

CALL DefaultLine
CALL CalculateArea(5, 3)

Python

ageCheck(21)

Examples

  • A Python program using procedures to display a menu and navigate between them

  • Procedures are defined at the start of the program and the main program calls the first procedure to start

  • In this example, no parameters are needed

Procedures

# Procedure definition for the main menu
def main_menu():
    # Outputs the options
    print("1. Addition") 
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")
    print("5. Exit")

    # Asks the user to enter their choice
    choice = int(input("Enter your choice: ")) 
    if choice == 1: 
        addition() 
    elif choice == 2:
        subtraction()
    elif choice == 3:
        multiplication()
    elif choice == 4:
        division()
    elif choice == 5:
        exit_program()

# Procedure definition for addition
def addition(): 
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: ")) 
    print("Result:", num1 + num2) 

# Procedure definition for subtraction
def subtraction():
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    print("Result:", num1 - num2)

# Procedure definition for multiplication
def multiplication():
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    print("Result:", num1 * num2)

# Procedure definition for division
def division():
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    if num2 != 0:
        print("Result:", num1 / num2)
    else:
        print("Error: Division by zero is not allowed.")

# Procedure to exit the program
def exit_program():
    print("Exiting the program. Goodbye!")
    exit()

# Main program
while True:  # Loop to continuously show the menu until the user chooses to exit
    main_menu()

Functions

  • Functions are defined using the FUNCTION keyword in pseudocode or def keyword in Python

  • Functions always return a value so they do not use the CALL function, instead they are called within an expression

  • A function can be written as:


    FUNCTION <identifier> RETURNS <data type>
    <statements>
    ENDFUNCTION

  • Or if parameters are being used:

    FUNCTION <identifier>(<param1>:<data type>, <param2>:<data type>...) RETURNS <data type>
    <statements>
    ENDFUNCTION

Creating and using a function

Pseudocode

FUNCTION CalculateArea(Length : INTEGER, Width : INTEGER) RETURNS INTEGER
    DECLARE Area : INTEGER
    Area ← Length * Width
    RETURN Area
ENDFUNCTION

// Output the value returned from the function
OUTPUT CalculateArea(5, 3)

Python

def squared(number):
    result = number ** 2
    return result

# Output the value returned from the function
print(squared(4))

Examples

  • A Python program using a function to calculate area and return the result

  • Two options for main program are shown, one which outputs the result (# 1) and one which stores the result so that it can be used at a later time (# 2)

Functions

# Function definition, length and width are parameters
def calculate_area(length, width):
    area = length * width  # Calculate area
    return area  # Return area

# Main program #1
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
print(calculate_area(length, width))  # Calls the function and prints the result

# Main program #2
length = int(input("Enter the length: "))  # Input for length
width = int(input("Enter the width: "))  # Input for width
calculated_area = calculate_area(length, width)  # Stores the result of the function in a variable
print("The area is " + str(calculated_area) + " cm^2")  # Outputs the result with a message

Worked Example

An economy-class airline ticket costs £199. A first-class airline ticket costs £595.

(A) Create a function, flightCost(), that takes the number of passengers and the type of ticket as parameters, calculates and returns the price to pay.

You do not have to validate these parameters

You must use :

  • pseudocode [4]

(B) Write program code, that uses flightCost(), to output the price of 3 passengers flying economy.

You must use :

  • pseudocode [3]

How do I answer this question?

(A)

  • Define the function, what parameters are needed? where do they go?

  • How do you calculate the price?

  • Return the result

(B)

  • How do you call a function?

  • What parameters does the function need to return the result?

Answers

A

FUNCTION FlightCost(Passengers : INTEGER, TicketType : STRING) RETURNS INTEGER
    DECLARE Cost : INTEGER
    IF TicketType = "economy"
      THEN
        Cost ← Passengers * 199
      ELSE
        Cost ← Passengers * 595
    ENDIF
    RETURN Cost
ENDFUNCTION
  • Function header with both parameters [1]

  • Selection on ticket type [1]

  • Correct calculation for both ticket types [1]

  • Value returned [1]

B

OUTPUT FlightCost(3, "economy")

OR

Price ← FlightCost(3, "economy")
OUTPUT Price

  • Function called by name [1]

  • Arguments in the correct order [1]

  • Result output [1]

Examiner Tips and Tricks

  • Use CALL only for procedures. A function returns a value, so use it inside an expression, for example OUTPUT CalculateArea(5, 3).

  • Give a data type for every parameter and for the value a function returns.

Unlock more, it's free!

Join the 100,000+ Students that ❤️ Save My Exams

the (exam) results speak for themselves:

Build on this topic

Robert Hampton

Author: Robert Hampton

Expertise: Curriculum Expert

Rob has over 16 years' experience teaching Computer Science and ICT at KS3 & GCSE levels. Rob has demonstrated strong leadership as Head of Department since 2012 and previously supported teacher development as a Specialist Leader of Education, empowering departments to excel in Computer Science. Beyond his tech expertise, Robert embraces the virtual world as an avid gamer, conquering digital battlefields when he's not coding.

James Woodhouse

Reviewer: James Woodhouse

Expertise: Portfolio Lead

James graduated from the University of Sunderland with a degree in ICT and Computing education. He has over 14 years of experience both teaching and leading in Computer Science, specialising in teaching GCSE and A-level. James has held various leadership roles, including Head of Computer Science and coordinator positions for Key Stage 3 and Key Stage 4. James has a keen interest in networking security and technologies aimed at preventing security breaches.