[ OCR J277 ERL ]

Module 7: Subroutines

What is a Subroutine?

A subroutine is a named block of code that performs a specific task. We use them to avoid repeating code, make the program easier to read, and modularise our software. There are two types: Procedures and Functions.

1. Procedures

A procedure performs a task but does not return a value back to the main program.

procedure greetPlayer(name)
    print("Welcome to the game, " + name)
endprocedure

greetPlayer("Alice") // Calling the procedure

Exercise: Procedures

Create a procedure called spacer that prints out a line of dashes "-----". Then call it twice.

ex1.erl

2. Functions

A function performs a task and returns a value using the return keyword.

function doubleNumber(x)
    return x * 2
endfunction

result = doubleNumber(5)
print(result) // Outputs 10

Exercise: Build a Function

Create a function called addNumbers that takes two parameters (a and b) and returns their sum. Then, call it with 10 and 15 and print the result.

ex2.erl

Global and Local Scope

Variables declared inside a subroutine are local to that subroutine and are destroyed when it ends. If you need a variable to be accessible everywhere, declare it with global.

global playerScore = 0
← Module 6 Next Module: File Handling →