Study Guide
Procedures and Functions
How to split a program into named, reusable parts: procedures and functions, with and without parameters, CALL and RETURN, local and global variables, the library routines MOD, DIV, ROUND and RANDOM, and why this makes programs easier to maintain.
Lesson 5.9 Algorithms and Programming
For: Cambridge IGCSE Computer Science learners, or Key Stage 3 learners who have met loops and selection (about ages 13 to 14)
Stage: Think
The same lines, again and again
A fictional school programme-printing program shows two notices. Each is framed by the same line of dashes, which is typed out in full every time it is needed:
OUTPUT "-----"
OUTPUT "Spring Concert"
OUTPUT "-----"
OUTPUT "Tickets: 40"
OUTPUT "-----"Think it through
The head teacher wants the line to be made of stars instead of dashes, and the real program has the line in thirty places. What is the problem? How could the program be arranged so that the change is made only once?
- Hint 1: What if you missed one of the thirty places?
- Hint 2: Could the line be written once and given a name?
Show a model answer
Thirty places means thirty edits, and missing one leaves an inconsistent program. It is better to write the line once, give it a name and use the name wherever the line is needed. Then the change is made in one place.
Stage: Discover
Naming a set of instructions
A named block of instructions that a program can use whenever it needs it is a subroutine. One kind, which carries out a task, is a procedure. It is defined once, between PROCEDURE and ENDPROCEDURE, at the start of the program, and called with CALL wherever it is needed.
PROCEDURE DrawLine
OUTPUT "-----"
ENDPROCEDURE
CALL DrawLine
OUTPUT "Spring Concert"
CALL DrawLine
OUTPUT "Tickets: 40"
CALL DrawLineDefining a procedure does not run it. The program starts at the first line that is not inside a definition, and each CALL passes control to the procedure, which carries out its lines and then returns to the line after the call.
| Order | Statement carried out in the main program | OUTPUT |
|---|---|---|
| 1 | CALL DrawLine | ----- |
| 2 | OUTPUT "Spring Concert" | |
| 3 | CALL DrawLine | |
| 4 | OUTPUT "Tickets: 40" | |
| 5 | CALL DrawLine |
Show the completed table
| Order | Statement carried out in the main program | OUTPUT |
|---|---|---|
| 1 | CALL DrawLine | ----- |
| 2 | OUTPUT "Spring Concert" | Spring Concert |
| 3 | CALL DrawLine | ----- |
| 4 | OUTPUT "Tickets: 40" | Tickets: 40 |
| 5 | CALL DrawLine | ----- |
The line of dashes is typed once, in the procedure. Changing it to stars changes all three places.
Check your understanding
Show the answer
Answer: A. DrawLine’s lines are carried out, then the program carries on after the CALL.
A procedure does nothing until it is called, and it can be called as many times as needed.
Stage: Predict
Giving a procedure something to work with
Think it through
A Welcome procedure is meant to show a different name each time it is used: “Welcome, Ravi”, then “Welcome, Chloe”. The lines inside it cannot be different each time. What must be different from one call to the next, and how could the procedure get it?
- Hint 1: The procedure’s lines stay the same. What does it need to be given?
Show a model answer
The name has to be different, so the program must hand the name to the procedure each time it calls it. The procedure then uses whatever name it was given.
A subroutine parameter, usually just called a parameter, is a variable in a subroutine’s definition that receives a value when the subroutine is called. It is written in brackets after the name, with its data type. The value supplied in the CALL is the argument.
PROCEDURE Welcome(Name : STRING)
OUTPUT "Welcome, ", Name
ENDPROCEDURE
CALL Welcome("Ravi")
CALL Welcome("Chloe")The first call outputs Welcome, Ravi, because Name receives “Ravi”; the second outputs Welcome, Chloe. A procedure can have up to three parameters, separated by commas. The arguments are matched to the parameters in order, and must be of the right data types.
PROCEDURE ShowTicket(Event : STRING, Row : INTEGER, Seat : INTEGER)
OUTPUT Event, ": row ", Row, ", seat ", Seat
ENDPROCEDURE
CALL ShowTicket("Concert", 4, 12)
CALL ShowTicket("Quiz", 1, 3)| Call | Event | Row | Seat | OUTPUT |
|---|---|---|---|---|
| CALL ShowTicket("Concert", 4, 12) | Concert | |||
| CALL ShowTicket("Quiz", 1, 3) |
Show the completed table
| Call | Event | Row | Seat | OUTPUT |
|---|---|---|---|---|
| CALL ShowTicket("Concert", 4, 12) | Concert | 4 | 12 | Concert: row 4, seat 12 |
| CALL ShowTicket("Quiz", 1, 3) | Quiz | 1 | 3 | Quiz: row 1, seat 3 |
The procedure’s lines do not change between calls. Only the values in its parameters do.
Do not confuse: Parameter and argument
- Where is it?Parameter
- In the definition: the named variable that receives a value.Name : STRING
- Where is it?Argument
- In the call: the actual value handed to the parameter."Ravi"
Their names need not match: the argument is matched to a parameter by its place in the list, not by its name.
Check your understanding
Show the answer
Answer: C. They are matched by position, so 12 goes to Event, a STRING, and “Concert” to Seat, an INTEGER.
Give the arguments in the same order, and of the same types, as the parameters.
Stage: Discover
A subroutine that gives back an answer
A ticket costs 6 pounds. A booking program needs the cost of 3 tickets and the cost of 2 tickets, and then their total.
Think it through
Suppose a procedure works out 3 × 6 = 18 and OUTPUTs it. Could the program then add this 18 to the cost of 2 tickets? Why, or why not? What would the subroutine have to do instead?
- Hint 1: OUTPUT shows a value on the screen. Does the rest of the program get it?
Show a model answer
No. OUTPUT puts the number on the screen, but the rest of the program never receives it. To be added to something else, the value must be handed back to the place in the program that asked for it.
A subroutine that works out one value and hands it back is a function. The value it hands back is its return value. Its definition states the data type with RETURNS, and the keyword RETURN hands the value back.
FUNCTION TicketCost(Tickets : INTEGER) RETURNS INTEGER
RETURN Tickets * 6
ENDFUNCTION
Total ← TicketCost(3) + TicketCost(2)
OUTPUT "Total: ", TotalA function call is not a statement on its own: it is part of an expression. When the function reaches RETURN, the value it hands back replaces the call in the expression, and the expression is then worked out. A function is called without CALL.
| Step | Call | Tickets | Value returned |
|---|---|---|---|
| 1 | TicketCost(3) | 3 | |
| 2 | TicketCost(2) | ||
| 3 | Total ← 18 + 12 |
Show the completed table
| Step | Call | Tickets | Value returned |
|---|---|---|---|
| 1 | TicketCost(3) | 3 | 18 |
| 2 | TicketCost(2) | 2 | 12 |
| 3 | Total ← 18 + 12 | 30 |
The program outputs Total: 30.
Do not confuse: Procedure and function
- What does it do?Procedure
- Carries out a task. It does not hand back a value.CALL DrawLine
- What does it do?Function
- Works out one value and returns it, to be used in an expression.Total ← TicketCost(3) + 2
A procedure is called with CALL, as a statement of its own. A function is never called with CALL: its call sits inside an expression, such as an assignment or an OUTPUT.
Check your understanding
Show the answer
Answer: B. OUTPUT "Cost: ", TicketCost(4)
A function call is used wherever its value is needed: in an output, an assignment, a condition or another call.
- State the job. Given two integers, hand back the larger. That is one value, so a function, with
RETURNS INTEGER. - Name the parameters. The two values are the parameters First and Second.
- Decide by comparison. If First is greater, the answer is First; otherwise it is Second. A local variable, Result, holds the choice.
- Return at the end.
RETURN Resultis the last statement.
FUNCTION Larger(First : INTEGER, Second : INTEGER) RETURNS INTEGER
DECLARE Result : INTEGER
IF First > Second
THEN
Result ← First
ELSE
Result ← Second
ENDIF
RETURN Result
ENDFUNCTION
OUTPUT Larger(8, 13)
Best ← Larger(Larger(4, 9), 6)
OUTPUT BestLarger(8, 13) returns 13, so the first output is 13. In the second statement the inner call Larger(4, 9) returns 9 first, and then Larger(9, 6) returns 9, so Best is 9.
Stage: Predict
Who can see which variable?
DECLARE Score : INTEGER
PROCEDURE AddBonus(Points : INTEGER)
DECLARE Bonus : INTEGER
Bonus ← Points * 2
Score ← Score + Bonus
ENDPROCEDURE
Score ← 0
CALL AddBonus(3)
CALL AddBonus(4)
OUTPUT ScoreThink it through
Predict what the program outputs. Then say whether a final line OUTPUT Bonus, added at the end of the program, would work, and why.
- Hint 1: Where is Bonus declared?
Show what happens
It outputs 14: the first call adds 3 × 2 = 6 and the second adds 4 × 2 = 8. OUTPUT Bonus would not work. Bonus is declared inside the procedure, so it only exists while the procedure is running, and the main program cannot use it.
A local variable is declared inside a subroutine, and can be used only there. It is created when the subroutine runs and is gone when it ends. A global variable is declared outside every subroutine, and can be used in the whole program, including inside subroutines. Parameters are local to their subroutine too.
| Moment | Points | Bonus | Score |
|---|---|---|---|
| Before the first call | - | does not exist | 0 |
| In the first call | 3 | ||
| In the second call | 4 | ||
| After the second call | - | does not exist |
Show the completed table
| Moment | Points | Bonus | Score |
|---|---|---|---|
| Before the first call | - | does not exist | 0 |
| In the first call | 3 | 6 | 6 |
| In the second call | 4 | 8 | 14 |
| After the second call | - | does not exist | 14 |
The program outputs 14.
Do not confuse: Local and global variables
- Where declared?Local variable
- Inside a subroutine. It can be used only there, and it disappears when the subroutine ends.Bonus in AddBonus
- Where declared?Global variable
- Outside all subroutines. Every part of the program can use it, and it lasts as long as the program runs.Score
Prefer local variables and parameters: a subroutine that uses only its own can be reused, and cannot change something else by accident.
DECLARE Level : INTEGER
PROCEDURE Reset
DECLARE Level : INTEGER
Level ← 0
ENDPROCEDURE
Level ← 5
CALL Reset
OUTPUT LevelHere a local variable has the same name as a global one.
Apply it
Show the answer
Answer: D. 5, because Reset changes its own local Level, not the global one.
Two variables can share a name if they are declared in different places, but they are not the same variable.
Stage: Discover
Subroutines that come ready-made
Think it through
A calculator shows 7.456. Predict the number you get when you round it to 1 decimal place, and to 0 decimal places (a whole number).
- Hint 1: Look at the digit after the place you are keeping.
Show what happens
To 1 decimal place it is 7.5, because the next digit, 5, rounds the 4 up. To 0 decimal places it is 7, because the next digit, 4, rounds down.
A library routine is a subroutine that is already written and ready to use, so that you do not write it yourself. The syllabus names four. DIV(a, b) is the whole number of times b goes into a, and MOD(a, b) is the remainder, as in Lesson 3. ROUND(value, places) rounds a number to a number of decimal places. RANDOM() returns a random number between 0 and 1.
| Expression | Result |
|---|---|
| DIV(17, 5) | 3 |
| MOD(17, 5) | |
| ROUND(3.14159, 2) | |
| ROUND(7.456, 1) | |
| ROUND(9.7, 0) |
Show the completed table
| Expression | Result |
|---|---|
| DIV(17, 5) | 3 |
| MOD(17, 5) | 2 |
| ROUND(3.14159, 2) | 3.14 |
| ROUND(7.456, 1) | 7.5 |
| ROUND(9.7, 0) | 10 |
The first row is given as an example.
- State the job. Show a number of minutes as whole hours and the minutes left over.
- Choose the routines. “Whole hours” is a DIV by 60, and “left over” is a MOD by 60.
- Write the procedure with one parameter.
PROCEDURE ShowDuration(Minutes : INTEGER)
OUTPUT DIV(Minutes, 60), " h ", MOD(Minutes, 60), " min"
ENDPROCEDURE
CALL ShowDuration(130)DIV(130, 60) is 2 and MOD(130, 60) is 10, so the output is 2 h 10 min.
A dice-rolling game needs a random whole number from 1 to 6. RANDOM() gives a number from 0 to 1, so RANDOM() * 5 gives a number from 0 to 5; ROUND of that is a whole number from 0 to 5, and adding 1 shifts the range to 1 to 6.
Die ← ROUND(RANDOM() * 5, 0) + 1Check your understanding
Show the answer
Answer: B. 1 and 6, because ROUND gives 0 to 5 and 1 is added.
Work out the smallest and largest value of each part, then combine them.
Stage: Explain
Programs that are easy to change
Think it through
Think back to the school notices in step 1 and the TicketCost function. Give two reasons why a program built from subroutines is easier to look after than one long list of lines.
- Hint 1: Think about what you would change, and where.
Show a model answer
Good reasons are: a change is made in one place, not in every copy; each subroutine can be tested and understood on its own; a name such as TicketCost tells the reader what a part is for; a subroutine can be reused in other programs; and different people can write different subroutines at once.
A program that is easy to understand and change later is maintainable. The syllabus links this to four habits: procedures and functions to avoid repeating code; meaningful identifiers for variables, constants, arrays, procedures and functions; comments (// in pseudocode) that explain what a section is for; and neat layout with indentation.
// Cost in pounds of a number of tickets, at 6 pounds each
FUNCTION TicketCost(Tickets : INTEGER) RETURNS INTEGER
RETURN Tickets * 6
ENDFUNCTIONCheck your understanding
Show the answer
Answer: C. Renaming X, Y and Z to TicketCount, TicketPrice and TotalCost, with comments.
Maintainable means that someone else, or you in six months’ time, can understand it quickly.
Stage: Apply
Spot the mistake
Sam (fictional) wants a function that doubles a number, and a line that uses it. The line that adds 1 outputs nothing sensible.
FUNCTION Double(Number : INTEGER) RETURNS INTEGER
OUTPUT Number * 2
ENDFUNCTION
Answer ← Double(7) + 1
OUTPUT AnswerApply it
Show the answer
Answer: A. It shows the doubled number but never returns it, so replace OUTPUT with RETURN.
A function that does not return a value gives its caller nothing to use.
Stage: Apply
Write one yourself
A fictional cinema charges by age: under 12 pays 5 pounds, 65 or over pays 6, and everyone else pays 8. A visitor’s age decides the price.
Think it through
Write a function TicketPrice that takes an age and returns the price. Then write the rest of a program that reads the ages of 3 visitors and outputs the total. Say what it outputs for ages 9, 70 and 30.
Work this out on paper or the board first. Nothing here is marked: compare yours with the model answer.
- Hint 1: Use a local variable to hold the price, with an IF to choose it.
- Hint 2: The total is set before the loop and the function is called inside it.
Show a model answer
FUNCTION TicketPrice(Age : INTEGER) RETURNS INTEGER
DECLARE Price : INTEGER
IF Age < 12
THEN
Price ← 5
ELSE
IF Age >= 65
THEN
Price ← 6
ELSE
Price ← 8
ENDIF
ENDIF
RETURN Price
ENDFUNCTION
Total ← 0
FOR Visitor ← 1 TO 3
INPUT Age
Total ← Total + TicketPrice(Age)
NEXT Visitor
OUTPUT "Total: ", TotalFor 9, 70 and 30 the prices are 5, 6 and 8, so the program outputs Total: 19. The function is defined first, and it is called inside the loop as part of an expression.
Go deeper The same ideas in Python
import random
def draw_line():
print("-----")
def show_ticket(event, row, seat):
print(f"{event}: row {row}, seat {seat}")
def ticket_price(age):
if age < 12:
price = 5
elif age >= 65:
price = 6
else:
price = 8
return price
score = 0
def add_bonus(points):
global score
bonus = points * 2
score = score + bonus
total = 0
for visitor in range(3):
age = int(input())
total = total + ticket_price(age)
print("Total:", total)
print(17 // 5, 17 % 5, round(3.14159, 2))
die = round(random.random() * 5) + 1- Python has one keyword,
def, for both. A subroutine that usesreturnis a function; one that does not is a procedure. There is noCALL: both are called by writing the name and the brackets,draw_line(). - Parameters are written without data types, in brackets after the name.
- A variable given a value inside a function is local. To change a global variable you have to say so with
global score; without it,score = ...would make a new local variable. //is DIV and%is MOD.round(x, places)is ROUND, but when a number ends exactly in 5 Python rounds to the nearest even digit, so do not rely on exact halves.random.random()gives a number from 0 up to, but not including, 1.ROUND(RANDOM() * 5, 0) + 1gives 1 and 6 only half as often as 2 to 5, because only half of the range rounds to them.random.randint(1, 6)gives each of 1 to 6 equally often, which is what a fair dice needs.
Stage: Consolidate
Show what you know
Think it through
Explain to a friend the difference between a procedure and a function, and between a parameter and an argument. Use the cinema or the concert as your example.
Show a model answer
A good answer says a procedure carries out a task and is called with CALL, such as showing a ticket, while a function works out a value and returns it with RETURN, such as TicketPrice(30) giving 8, so its call is used in an expression. A parameter is the named variable in the definition (Age), and an argument is the actual value given in the call (30), matched by position.
Apply it
Show the answer
Answer: C. A procedure for the heading, because it shows something, and a function for the fine.
Choose a procedure when the subroutine does something, and a function when it works something out.
- A subroutine is a named, reusable block. A procedure carries out a task and is called with
CALL. A function returns one value (RETURNS,RETURN) and is called inside an expression, withoutCALL. - A parameter is the variable in the definition; an argument is the value in the call. Arguments are matched to parameters by position and type. A subroutine may have up to three parameters.
- A local variable exists only inside its subroutine; a global variable can be used everywhere. A local variable with the same name as a global one is a separate variable.
- Library routines are ready-made: DIV and MOD for whole number and remainder, ROUND for decimal places, RANDOM for a random number from 0 to 1.
- Subroutines, meaningful names and comments make a program maintainable: a change is made in one place and each part can be understood alone.
- Usual faults: calling a function with CALL, forgetting RETURN, giving arguments in the wrong order, and using a local variable outside its subroutine.
Sources and scope
- What this lesson is. The ninth lesson of the Algorithms and Programming module, written for this site. It covers points 8.1.6 and 8.1.7 of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6) and part of 8.1.8. Its curriculum links are provisional and imply no review or endorsement by any examination board.
- Original material. The school programme notices, the ticket booking, the cinema, the library and Sam are fictional, written for this lesson. The pseudocode follows the layout of the syllabus’s pseudocode guide (definitions at the start,
CALLfor procedures only), and every output was worked out by hand and checked with an equivalent Python program. - Simplified on purpose. Parameters are passed as values only; passing by reference is not part of 0478. Each function has a single RETURN at the end. The exact rules for a local variable with the same name as a global one differ between languages; the lesson shows the usual behaviour, and the pseudocode guide does not describe it.
- Left to later lessons. Arrays as parameters and return values, and recursion, are not taught here. Arrays are in Lesson 10.
A sequence of precise steps that solves a problem or completes a task.
The actual value supplied for a parameter when a subroutine is called.
A statement that stores a value in a variable. In Cambridge pseudocode it is written with an arrow, for example Score ← 0.
An expression that is either true or false, such as Age >= 12, used to decide what a program does next.
A named value that is set once and does not change while the program runs.
The kind of value a variable holds, such as a whole number or text. It decides what the program can do with the value.
The everyday number system with ten digits, 0 to 9, in which each column is worth ten times the column to its right.
A subroutine that works out one value and returns it, to be used in an expression. It is defined with FUNCTION … RETURNS … ENDFUNCTION and ends with RETURN.
A variable declared outside every subroutine. It can be used in the whole program, including inside subroutines.
The data type for whole numbers, positive, negative or zero, such as 5 or -3.
A ready-made subroutine that a programming language supplies, such as MOD, DIV, ROUND and RANDOM.
A variable declared inside a subroutine. It can be used only there, and it disappears when the subroutine ends.
A set of instructions that is repeated, either a fixed number of times or until a condition says to stop.
One of the numbers inside a model that are set during training. Together they hold the patterns the model learnt.
A variable named in a subroutine’s definition that receives a value when the subroutine is called. It is usually just called a parameter.
A subroutine that carries out a task and does not return a value. It is defined with PROCEDURE … ENDPROCEDURE and used with CALL.
A precise but language-independent way of writing an algorithm, with set keywords such as IF, WHILE and OUTPUT, that is not tied to any one programming language.
A high-level programming language written as text, popular for learning and for real work, in which indentation shows which lines belong together.
The value that a function hands back to the place that called it, using RETURN.
A named block of instructions, written once and used whenever it is needed. Procedures and functions are subroutines.
A named place in memory that stores a value which can change while a program runs.
Your progress on this lesson
Saved in this browser only. It is not sent anywhere, does not follow you to another device, and is lost if you clear this site’s data.
This browser is not allowing the site to save progress, so it will be forgotten when you leave the page.