Define and use a procedure and explain where in construction of an algorithm it would be appropriate to use a procedure
Use parameters effectively in procedures and functions
Define and use a function and explain where in construction of an algorithm it is appropriate to use a function
Use terminology associated with procedures and functions correctly
Understand the difference between passing parameters by value and by reference
Write efficient pseudocode using procedures and functions
🌟 Did You Know?
When writing programs, we should avoid long, repetitive code. Procedures and functions help to keep our programs simple and short. They are fundamental building blocks in structured programming that enable decomposition - breaking down complex problems into smaller, manageable sub-tasks!
📋 Prior Knowledge Required
Basic understanding of programming constructs (sequence, selection, iteration)
Knowledge of variables and data types
Understanding of how to write simple algorithms in pseudocode
Ability to use INPUT and OUTPUT statements
Understanding of arrays and basic data structures
1. What are Functions and Procedures For?
Decomposition is a problem-solving technique that involves breaking down a complex problem into smaller, more manageable sub-tasks. Each sub-task can be considered as a 'module' or Subroutine.
📖 Definition: Modules
Modules are of two types: Functions and Procedures.
User-defined subroutines are written by programmers and used only in that specific program in which they are written.
1.1 Why Use Subroutines?
✅ Advantages of Using Subroutines
Reusability: Subroutine code can be called from many/multiple places
Subroutine code may be independently tested and debugged
If subroutine task changes, the change needs to be made only once
Reduces unnecessary duplication of program lines, reducing length of code
Enables sharing of development between programmers
Can share amongst other programmers to avoid everyone rewriting
Can use in multiple programs without rewriting
Less chance of errors as do not need to re-write / re-test
One change in function will be applied in all places used
💡 Real-Life Analogy
A real-life example of a procedure is brushing your teeth. There are several steps involved: getting your toothbrush, squeezing toothpaste onto the brush, brushing all teeth, rinsing your mouth, and putting everything away. Each time you brush your teeth, you follow this same procedure - just like calling a subroutine in a program!
⚠️ Key Distinction
Both functions and procedures are small sections of code that can be repeated through a program. The difference between them is:
Procedures perform a specific task but do NOT return a value
Functions perform a task and RETURN a value to the main program
2. Procedures
A procedure groups together a number of steps and gives them a name known as an identifier. We can use this identifier when we want to refer to this group of steps.
📖 Key Characteristics of Procedures
A procedure is defined once and can be called many times within a program
When we want to write a procedure, we need to define it before the main program
We call it in the main program when we want the statements in the procedure body to be executed
Procedures do NOT return a value to the calling program
When parameters are used, values must be of the correct data type and in the same sequence.
2.2 Procedure Example: Without Parameters
PROCEDURE Message()
OUTPUT "CS Made Easy"
ENDPROCEDURE
// To call this procedure:
CALL Message()
2.3 Procedure Example: With Parameters
PROCEDURE total(Num1 : INTEGER, Num2 : INTEGER)
Total ← Num1 + Num2
OUTPUT "Sum of Numbers = ", Total
ENDPROCEDURE
// To call this procedure:
CALL total(9, 5)
2.4 Procedure Example: Input Validation
PROCEDURE InputOddNum()
REPEAT
INPUT "Enter an odd number: " Num
UNTIL Num MOD 2 = 1
OUTPUT "Valid number entered"
ENDPROCEDURE
// To call this procedure:
CALL InputOddNum()
3. Procedures in Python
Consider this excerpt from a Python game program which prints player information on the screen:
Suppose you wanted to print out the player information at these different points in the game:
At the end of a level
When the player loses a life
When the player beats the high score
When the game is over
You would need to repeat those six lines of code on each occasion, giving a total of 24 lines of code simply to display the player information!
3.1 Creating a Procedure in Python
To create a procedure, first give the procedure a name. A good name for the player information procedure could be update_display. Use the def statement to name a procedure:
Once a procedure is named and written, it can be called at any point in the program. Simply use its name (include the brackets):
# End of level
update_display()
# Lose a life
update_display()
# Beat high score
update_display()
# Game over
update_display()
🌟 Code Reduction
Using this procedure greatly reduces the amount of code that has to be included in the program. Instead of 24 lines, you now have just 6 lines in the procedure + 4 calls = 10 lines total!
4. Functions
A function groups together a number of steps and gives them a name known as an identifier. Functions operate in a similar way to procedures, except that in addition they return a single value to the point at which they were called.
📖 Key Characteristics of Functions
Functions always return a value
Function definition includes data type of value returned
Must always include a RETURN statement
Do NOT use keyword CALL when calling a function
Functions should only be called as part of an expression
You can have more than one RETURN statement if there are different paths through the function
4.1 Function Syntax in Pseudocode
📝 Function Definition Format
FUNCTION <functionIdentifier>(<parameterList>) RETURNS <dataType>
<statement(s)>
RETURN <value>
ENDFUNCTION
4.2 Function Example: Odd Number Input
FUNCTION InputOddNumber() RETURNS INTEGER
REPEAT
INPUT "Enter an odd number: " Num
UNTIL Num MOD 2 = 1
OUTPUT "Valid number entered"
RETURN Num
ENDFUNCTION
// To call this function:
X ← InputOddNumber()
4.3 Function Example: Maximum of Two Numbers
FUNCTION Max(Number1: INTEGER, Number2: INTEGER) RETURNS INTEGER
IF Number1 > Number2 THEN
RETURN Number1
ELSE
RETURN Number2
ENDIF
ENDFUNCTION
// Using (calling) the function:
OUTPUT "Max Number is = ", Max(10, 2)
💡 Important Note
When a subroutine is called, we supply arguments in brackets. Arguments supplied are assigned to the corresponding parameter of the subroutine.
The order of parameters in the parameter list must be the same as the order in the list of arguments. This is known as the subroutine interface.
4.4 Python Function Example: Dice Roll
Look at this excerpt from a Python role-playing game program which simulates the throwing of a dice:
import random
def roll_dice(sides):
number = random.randint(1, sides)
return number
sides = int(input("How many sides does the dice have?"))
throw = roll_dice(sides)
print(throw)
5. Procedures vs Functions Comparison
Feature
Procedure
Function
Returns a value?
NO
YES
Called using
CALL statement
Part of an expression
Primary purpose
Perform a task
Calculate and return a value
Use when you need
To execute actions without returning data
A result or calculated value
Example use case
Display menu, print report, update display
Calculate sum, find maximum, validate input
Can use BYREF?
Yes
No (should not)
🧠 Memory Trick
Procedure = Performs a task (like a recipe - just does something)
Function = Finds an answer (like a calculator - gives you a result)
6. Parameter Passing
Parameter passing is the method by which values or references are given to procedures or functions so they can use or modify data during execution.
📖 Key Terminology
Parameter: A variable applied to a procedure or function that allows one to pass in a value for the procedure to use
Argument: The value passed to a procedure or function
Header: The first statement in the definition of a procedure or function, which contains its name, any parameters, and (for functions) the return type
6.1 BYVAL (By Value)
📝 Passing Parameters By Value
If a parameter is passed by value, at call time the argument can be an actual value
If the argument is a variable, then a copy of the current value of the variable is passed into the subroutine
The value of the variable in the calling program is NOT affected by what happens in the subroutine
6.2 BYREF (By Reference)
📝 Passing Parameters By Reference
At call time, the argument must be a variable
A pointer to the memory location of that variable is passed into the procedure
When parameters are passed by reference, when values inside the subroutine change, this affects the values of variables in the calling program
Keyword
What It Does
BYVAL
Passes a copy of the value (no change to original)
BYREF
Passes a reference to the variable (can be modified)
⚠️ Important Rules
If no keyword is used, it is assumed to be BYVAL
Functions should NOT use BYREF parameters – only procedures should
7. BYVAL vs BYREF Examples
7.1 BYVAL Example
PROCEDURE OutputSymbols(BYVALUE NumberOfSymbols : INTEGER, Symbol : CHAR)
DECLARE Count : INTEGER
FOR Count ← 1 TO NumberOfSymbols
OUTPUT Symbol // without moving to next line
NEXT Count
ENDPROCEDURE
// To call this procedure:
CALL OutputSymbols(6, '*')
Output: ******
7.2 BYREF Example: Swapping Values
PROCEDURE Swap(BYREF X : INTEGER, BYREF Y : INTEGER)
DECLARE Temp : INTEGER
Temp ← X
X ← Y
Y ← Temp
ENDPROCEDURE
// Main program
A ← 5
B ← 10
CALL Swap(A, B)
OUTPUT A, B // Output: 10, 5
💡 What Happens?
When Swap is called with BYREF:
X and Y point to the SAME memory locations as A and B
Any changes to X and Y inside the procedure also change A and B
After the procedure, A = 10 and B = 5 (values swapped!)
8. Worked Example
Question: A video-conferencing program supports up to six users. Speech from each user is sampled and digitised. Digitised values are stored in array Sample.
The array Sample consists of 6 rows by 128 columns and is of type integer. Each row contains 128 digitised sound samples from one user.
The digitised sound samples from each user are to be processed to produce a single value which will be stored in a 1D array Result of type integer. This process will be implemented by procedure Mix().
A procedure Mix() will:
Calculate the average of each of the 6 sound samples in a column
Ignore sound sample values of 10 or less
Store the average value in the corresponding position in Result
Repeat for each column in array Sample
Write pseudocode for procedure Mix(). Assume Sample and Result are global. [6 marks]
8.1 Solution
PROCEDURE Mix()
DECLARE Count, Total, ThisNum : INTEGER
DECLARE ThisUser, ThisSample : INTEGER
FOR ThisSample ← 1 TO 128
Count ← 0
Total ← 0
FOR ThisUser ← 1 TO 6
IF Sample[ThisUser, ThisSample] > 10 THEN
Count ← Count + 1
Total ← Total + Sample[ThisUser, ThisSample]
ENDIF
NEXT ThisUser
Result[ThisSample] ← INT(Total / Count)
NEXT ThisSample
ENDPROCEDURE
📝 Mark Scheme Breakdown
Declaration and initialisation before inner loop of Count and Total [1 mark]
Outer Loop for 128 iterations [1 mark]
Inner loop for six iterations [1 mark]
Test for sample > 10 in a loop [1 mark]
And if true sum Total and increment Count [1 mark]
Calculate average value and assign to Result array after inner loop [1 mark]
Use of INT()/DIV to convert average to integer [1 mark - bonus]
9. Exam-Style Questions
1. Explain the difference between a procedure and a function. [4 marks]
Answer:
A procedure does not return a value to the calling program
A function returns a single value to the point where it was called
Procedures are called using the CALL statement
Functions are called as part of an expression (not using CALL)
Additional point: Functions must include a RETURN statement; procedures do not
Additional point: Functions should not use BYREF parameters; procedures can
2. Write a procedure called DisplayStars that takes one integer parameter and outputs that number of asterisks (*) on the same line. [4 marks]
Answer:
PROCEDURE DisplayStars(NumberOfStars : INTEGER)
DECLARE Count : INTEGER
FOR Count ← 1 TO NumberOfStars
OUTPUT "*" // without moving to next line
NEXT Count
ENDPROCEDURE
Additional points for deeper understanding:
The procedure uses a loop to iterate the correct number of times
OUTPUT without newline keeps stars on same line
3. Write a function called CalculateArea that takes two integer parameters (length and width) and returns the area as an integer. [4 marks]
Answer:
FUNCTION CalculateArea(Length : INTEGER, Width : INTEGER) RETURNS INTEGER
DECLARE Area : INTEGER
Area ← Length * Width
RETURN Area
ENDFUNCTION
Additional points:
Function header includes RETURNS keyword with data type
RETURN statement is mandatory in functions
Can be called as: Result ← CalculateArea(5, 3)
9. Exam-Style Questions (Continued)
4. Explain the difference between passing a parameter by value (BYVAL) and by reference (BYREF). [4 marks]
Answer:
BYVAL passes a copy of the value to the subroutine
Changes made to the parameter do not affect the original variable
BYREF passes a pointer to the memory location of the variable
Changes made to the parameter do affect the original variable
Additional: BYREF requires the argument to be a variable (not a literal value)
Additional: BYVAL is the default if no keyword is specified
5. Write a function MakeString() that takes two parameters: a count (integer) and a character. It should generate and return a string of length equal to count, made up of the character. Return "ERROR" if count is less than 1. [5 marks]
Answer:
FUNCTION MakeString(Count : INTEGER, Char : CHAR) RETURNS STRING
DECLARE Result : STRING
DECLARE i : INTEGER
Result ← ""
IF Count < 1 THEN
RETURN "ERROR"
ENDIF
FOR i ← 1 TO Count
Result ← Result + Char
NEXT i
RETURN Result
ENDFUNCTION
Example: MakeString(3, 'Z') returns "ZZZ"
6. A procedure CountVowels() takes a string parameter and counts the occurrences of each vowel (a, e, i, o, u). Counts are stored in a global 1D array CharCount[6] of type INTEGER. Write pseudocode for this procedure. [6 marks]
Answer:
PROCEDURE CountVowels(Text : STRING)
DECLARE i : INTEGER
DECLARE Char : CHAR
// Initialize array
FOR i ← 1 TO 6
CharCount[i] ← 0
NEXT i
FOR i ← 1 TO LENGTH(Text)
Char ← UCASE(Text[i])
IF Char = 'A' THEN CharCount[1] ← CharCount[1] + 1
ELSE IF Char = 'E' THEN CharCount[2] ← CharCount[2] + 1
ELSE IF Char = 'I' THEN CharCount[3] ← CharCount[3] + 1
ELSE IF Char = 'O' THEN CharCount[4] ← CharCount[4] + 1
ELSE IF Char = 'U' THEN CharCount[5] ← CharCount[5] + 1
ELSE IF Char >= 'A' AND Char <= 'Z' THEN
CharCount[6] ← CharCount[6] + 1 // Other letters
ENDIF
NEXT i
ENDPROCEDURE
9. Exam-Style Questions (Continued)
7. Describe three advantages of using subroutines in a program. [3 marks]
Answer (any three):
Reusability: Code can be called from multiple places
Maintainability: Changes only need to be made once
Testing: Subroutines can be tested independently
Readability: Code is easier to understand
Collaboration: Different programmers can work on different subroutines
Reduced errors: Less code duplication means fewer chances for mistakes
8. Write a procedure Swap() that exchanges the values of two integer variables passed by reference. [4 marks]
Answer:
PROCEDURE Swap(BYREF X : INTEGER, BYREF Y : INTEGER)
DECLARE Temp : INTEGER
Temp ← X
X ← Y
Y ← Temp
ENDPROCEDURE
Key points:
BYREF is essential - otherwise original values wouldn't change
Temporary variable is needed to hold one value during swap
Without Temp, one value would be lost
9. Write a function Max() that takes two integer parameters and returns the larger value. [4 marks]
Answer:
FUNCTION Max(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER
IF Number1 > Number2 THEN
RETURN Number1
ELSE
RETURN Number2
ENDIF
ENDFUNCTION
Usage: OUTPUT "Max is: ", Max(10, 25) // Outputs: Max is: 25
10. Explain why functions should not use BYREF parameters. [3 marks]
Answer:
Functions are designed to return a single value through the RETURN statement
Using BYREF creates a "side effect" - modifying variables outside the function
This makes code harder to debug and understand
It violates the principle that functions should be pure (no side effects)
If you need to modify multiple values, use a procedure with BYREF instead
10. Glossary
Subroutine
A named block of code that performs a specific task and can be called from anywhere in the program. Includes both procedures and functions.
Procedure
A subroutine that performs a specific task but does NOT return a value to the calling program. Called using the CALL statement.
Function
A subroutine that performs a calculation or task and RETURNS a single value to the calling program. Called as part of an expression.
Parameter
A variable in a subroutine definition that accepts a value passed in from the calling program.
Argument
The actual value or variable passed to a subroutine when it is called.
BYVAL (By Value)
A method of passing parameters where a copy of the value is passed. Changes to the parameter do not affect the original variable.
BYREF (By Reference)
A method of passing parameters where a pointer to the variable's memory location is passed. Changes to the parameter DO affect the original variable.
Header
The first line of a subroutine definition that includes the name, parameter list, and (for functions) return type.
Decomposition
Breaking down a complex problem into smaller, more manageable sub-tasks (modules).
Identifier
The name given to a subroutine, variable, or other programming element.
RETURN Statement
A statement in a function that sends a value back to the calling program and exits the function.
Module
A self-contained section of code that performs a specific task. Also called a subroutine.
11. Exam Success Tips (Part 1)
💡 Procedure vs Function - Quick Check
Procedure: Does a task, no return value, use CALL
Function: Calculates a value, returns it, use in expression
Ask yourself: "Do I need a result back?" If YES → Function; If NO → Procedure
💡 BYVAL vs BYREF - Remember This!
BYVAL = Makes a COPY (original stays same)
BYREF = Uses the ORIGINAL (changes affect it)
Think: BYVAL = "By Value" = Copy the Value; BYREF = "By Reference" = Point to it
🧠 Memory Trick: The Parameter Rules
VALUE = VARIABLE stays same (protected)
REFerence = REFlects changes (can be modified)
Default is BYVAL if not specified
Functions should NOT use BYREF!
❌ Common Mistakes to Avoid
Don't use CALL with functions - they're called in expressions
Don't forget RETURN in functions - it's mandatory!
Don't mix up parameters (in definition) with arguments (when calling)
Don't use BYREF with functions - only procedures
Don't forget to declare local variables inside subroutines
⚠️ Exam Writing Tips
Always write the full header: PROCEDURE/FUNCTION name(params) [RETURNS type]
Remember ENDPROCEDURE or ENDFUNCTION at the end
Indent code inside subroutines properly
Show parameter data types: (Num : INTEGER, Name : STRING)