O & A Level Computer Science P2/P4 Procedures & Functions N.
Procedures and Functions
A subroutine is a self-contained piece of code that has an identifier (name), and it can be called
from anywhere in the main program.
A subroutine can be classified as a procedure or a function.
• A procedure is a set of programming statements grouped together under a single name
that can be called to perform a task at any point in a program. It does not return a value
to the main program.
• A function is a set of programming statements grouped together under a single name
in
that can be called to perform a task at any point in a program. A function returns a value
back to the main program.
➢ Subroutines are useful because they reduce code and reduce the chances of error.
st
Procedures and functions can both take one or more values as parameters.
u
g
• A function is like a procedure, except it always returns a value.
• Like a procedure, it is defined once and can be called many times within a program,
• and be defined with or without parameters.
u
A
Parameters are the variables that store the values of the arguments passed to a procedure or
function. Some procedures and functions will have parameters.
r.
➢ Parameter: a value that is sent to a subroutine.
M
Procedures and functions are defined once and can be called many times within a program.
When procedures and functions are defined, the first statement in the definition is a header,
which contains:
• the name of the procedure or function
• any parameters passed to the procedure or function
• the type of the return value for a function.
Page 1 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
The main differences between procedures and functions are:
• Functions return a single value through their identifier.
• Procedures output zero or more values through their parameters.
Procedures
A procedure runs the code inside it, and does not return a value. The structure of a procedure is:
PROCEDURE identifier()
code to run inside the function
END PROCEDURE
in
The identifier is then used in the main program.
The procedure is called from the main code as follows:
st
CALL identifier()
VB syntax is:
u
g
Start of the Name of the
procedure procedure
u
Parameter values
Sub MyFirstSub()
are put in ()
A
End Sub
End of the
procedure
r.
Sub Main ()
Call MyFirstSub()
M
End Sub
Example 1
A procedure to output the numbers 1 to 10:
PROCEDURE OutputlTol0()
FOR Count ← 1 T0 10
OUTPUT(Count)
NEXT Count
END PROCEDURE
Page 2 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
The main program can then call the procedure with the code:
OutputlTol0() or
CALL Output1To10()
Module Program
Sub Main()
outputlTol0() 'or Call output1To10()
End Sub
Sub outputlTol0()
For count = 1 To 10
Console.WriteLine(count)
Next
in
End Sub
End Module
Example 2
A procedure to take two numbers from the user and multiply then together:
st
PROCEDURE Multiply()
OUTPUT ("Enter a number")
INPUT Numl
u
OUTPUT ("Enter a second number")
g
INPUT Num2
Total ← Numl * Num2
u
END PROCEDURE
A
The procedure can be called in the main program with the code:
multiply() or CALL multiply()
r.
Module Program
Sub Main()
M
Call multiply() 'or multiply()
End Sub
Sub multiply()
Dim numl, num2, total As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine()
Console.WriteLine("Enter a second number")
num2 = Console.ReadLine()
total = numl * num2
End Sub
End Module
Page 3 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Function
A function returns a value to the program that called it. This can be by either using the RETURN
command, or saving a value to the function's identifier. Once a value is returned, the function stops
running, so it cannot have any code after otherwise this will not run.
It has the structure:
FUNCTION identifier()
Code to run in the function
RETURN value
in
ENDFUNCTION
VB syntax is:
st
Function MyFirstFunc()
End Function
u
g
When the function is called it returns a value, so something needs to happen with this value.
It could be output, e.g.
u
OUTPUT(function identifier)
A
or it could be saved in a variable, e.g.
variable identifier= function identifier
r.
Example 1
M
Write a function to ask the user to enter two values, add them together and return the
value:
FUNCTION Multiply()
OUTPUT ("Enter a number")
INPUT Numl
OUTPUT ("Enter another number")
INPUT Num2
RETURN Numl * Num2
ENDFUNCTION
Page 4 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
To output the return value the main program can use:
OUTPUT(Multiply())
Module Program
Sub Main()
Console.WriteLine(multiply())
End Sub
Function multiply()
Dim numl, num2 As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine()
in
Console.WriteLine("Enter a second number")
num2 = Console.ReadLine()
Return numl * num2
End Function
End Module
st
Example 2
u
Write a function to total all the values in an array with 50 elements and then return the
g
total:
FUNCTION TotalValues()
u
Total ← 0
FOR X ← 0 TO 49
A
Total ← Total + Array[X]
NEXT X
r.
RETURN Total
END FUNCTION
M
To store the return value in a variable in the main program:
Total = TotalValues()
Page 5 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Sub Main()
Dim total As Integer
total = totalValues()
Console.WriteLine("The total is " & total)
End Sub
Function totalValues()
Dim arrayData(49) As Integer
Dim total As Integer = 0
'Populate array
For x = 0 To 49
Console.Write("Please enter a value: ")
arrayData(x) = Console.ReadLine()
total = total + arrayData(x)
in
Next
Return total
End Function
End Module
Scope
st
u
The scope of a variable is the areas within a program that it can be accessed.
g
There are two scopes: global and local.
u
Global scope: the variable or constant can be accessed from any part of the program.
Local scope: the variable or constant can only be accessed in the subroutine it is declared within.
A
Global variable is declared at the top of the program.
r.
Example 1
M
Declaring a global variable, then outputting its value twice. Once in the main program, and once in a
procedure call.
GLOBAL Data
PROCEDURE OutputData()
OUTPUT(Data)
END PROCEDURE
//main program
Data ← 1
OUTPUT(Data)
OutputData()
Page 6 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Module Program
Dim data As Integer
Sub outputData()
Console.WriteLine(data)
End Sub
Sub Main()
data = 1
Console.WriteLine(data)
outputData()
End Sub
End Module
in
• If you declare a variable (or constant, or array) as local, then it can only be accessed in the
part of the code where it is declared.
• If you declare it first in a subroutine, then it can only be accessed within that subroutine.
• If you declare it in the main program, it can only be accessed in the main program.
Example 2
st
u
Creating a local variable to the main program and outputting it twice. Once in the main program, and
once from a subroutine where it is sent as a parameter.
g
PROCEDURE OutputData(DataParameter)
OUTPUT(DataParameter)
u
END PROCEDURE
Data ← 1
A
OUTPUT(DataParameter)
OutputData(Data)
r.
Module Program
M
Sub outputData(dataParameter)
Console.WriteLine(dataParameter)
End Sub
Sub Main()
Dim data As Integer
data = 1
Console.WriteLine(data)
outputData(data)
End Sub
End Module
Page 7 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Parameters
A parameter is a value that is sent from the main program to the subroutine (procedure or
function).
Parameters are declared inside the brackets after the subroutines name, e.g.
PROCEDURE identifier(parameterl, parameter2 ... )
Code to run
END PROCEDURE
in
or
FUNCTION identifier(parameterl, parameter2 ... )
Code to run
st
ENDFUNCTION
u
If a subroutine is declared with parameters, then it must be called with the same number of
parameters. For example:
g
PROCEDURE Total(Numl, Num2)
Code to run
u
END PROCEDURE
A
This has two parameters. When the procedure is called it must have 2 numbers sent to it. This could be
numbers, e.g.
Total(l,2)
r.
or variables. e.g.
Total(Numberl, Number2)
M
Example 1
A function takes two numbers, divides them and returns the result:
FUNCTION Division(First, Second)
RETURN First/ Second
END FUNCTION
Page 8 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
The main program sends 10 and 2, then outputs the return value.
OUTPUT(Division(l0, 2))
Module Program
Sub Main()
Console.WriteLine(division(10, 2))
End Sub
Function division(first, second)
Return first / second
End Function
End Module
in
Example 2
A procedure takes 2 values and outputs all the numbers between the first number to the second:
PROCEDURE OutputNumbers(Numl, Num2)
st
FOR Count ← Numl TO Num2
OUTPUT Count u
NEXT Count
END PROCEDURE
g
The main program taking two values from the user.
OUTPUT("Enter the smallest number")
u
INPUT FirstNumber
OUTPUT("Enter the largest number")
A
INPUT SecondNumber
OutputNumbers(FirstNumber, SecondNumber)
r.
M
Module Program
Sub Main()
Console.WriteLine("Enter the smallest number")
Dim firstNumber As Integer = Console.ReadLine
Console.WriteLine("Enter the largest number")
Dim secondNumber As Integer = Console.ReadLine
outputNumbers(firstNumber, secondNumber)
End Sub
Sub outputNumbers(numl, num2)
For count = numl To num2
Console.WriteLine(count)
Next
End Sub
End Module
Page 9 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Passing parameter values (with data type)
➢ Function
Example: Design a function that takes the radius of a circle as a parameter and returns the area of
that circle.
The VB syntax for a function is:
Start of the Name of the Return value
data type
function function
Function Circle (R As Decimal) As Decimal
in
Incoming
parameters
End Function
End of the
st
function
The pseudocode syntax is:
FUNCTION Circle (R : REAL) RETURNS REAL
u
g
ENDFUNCTION
u
Solution
A
Pseudocode for main program:
DECLARE Radius, AREA : REAL
OUTPUT “Enter Radius: “
r.
INPUT Radius
Area ← Circle(Radius)
M
Pseudocode for function:
FUNCTION Circle (R: REAL) RETURNS REAL
CONSTANT Pi ← 3.14
RETURN R * R * Pi
ENDFUNCTION
Page 10 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Module Program
'The main code that will call the function
Sub Main()
Dim Radius, Area As Decimal
Console.Write("Enter radius: ")
Radius = Console.ReadLine()
'The variable area is assigned the return value from the function
'The function is passed the value within the variable 'Radius'
Area = Circle(Radius)
Console.WriteLine(Area)
Console.ReadKey()
End Sub
Function Circle(R As Decimal) As Decimal
Const Pi As Decimal = 3.14
Return R * R * Pi
in
End Function
End Module
st
It is also possible to use the returned value directly in the Console.Writeline command:
Sub Main()
Dim Radius As Decimal
u
Console.Write("Enter Radius: ")
g
Radius = Console.ReadLine()
Console.WriteLine(Circle(Radius))
Console.ReadKey()
End Sub
u
A
➢ Procedure
Passing parameters by value or reference *A Level
r.
Functions pass their return value through their identifier. As a result, there is no need to consider
whether parameters are ingoing or outgoing.
M
Procedures use parameters to identify both ingoing and outgoing values. So there is a need to
differentiate between ingoing and outgoing parameters.
Parameters can be passed by value or by reference.
Passing by value
• The subroutine holds a local copy of the data passed.
• Any changes made to the data are held in the local copy within the subroutine.
• If the data passed originated from a variable in the main code, the original value in that
variable remains unaltered.
Page 11 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Passing by reference
• The subroutine is passed a value by reference to a variable or array declared in the main
code that holds the data to be used.
• Any changes made to that value is stored in the referenced variable in the main code.
A procedure with parameters passed by reference can be defined in pseudocode as follows:
PROCEDURE <identifier> (BYREF <parameter1>:<datatype>,
<parameter2>:<datatype>...)
<statements>
in
ENDPROCEDURE
st
For example, a procedure to convert a temperature from Fahrenheit to Celsius could be defined as
follows:
Or BYVAL
PROCEDURE celsius(BYREF temperature : REAL)
u
temperature ← (temperature – 32) / 1.8
g
ENDPROCEDURE
u
And used as follows:
A
CALL celsius(myTemp)
r.
VB Syntax:
Sub celsius(ByVal temperature As Decimal)
M
Sub celsius(ByRef temperature As Decimal)
Page 12 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Example of the use of ByRef
Sub Main()
Dim num As Integer = 10
Console.WriteLine("Original value of num: " & num)
' Call the ModifyByReference function
Call ModifyByReference(num)
Console.WriteLine("Modified value of num: " & num)
End Sub
Sub ModifyByReference(ByRef value As Integer)
' Modify the value passed by reference
value = value + 5
End Sub
in
The output:
st
In this program:
•
•
u
We declare a variable num and initialize it with the value 10.
We call the ModifyByReference function, passing num by reference using the ByRef
keyword.
g
• Inside the function, we modify the value of num by adding 5.
• When we print the value of num after the function call, we see that it has been modified to
15.
u
A
Example of the use of ByVal
Sub Main()
Dim num As Integer = 10
Console.WriteLine("Original value of num: " & num)
r.
' Call the ModifyByValue function
ModifyByValue(num)
M
Console.WriteLine("Value of num after ModifyByValue: " & num)
End Sub
Sub ModifyByValue(ByVal value As Integer)
' Modify the local copy of the value (not affecting the original
variable)
value = value + 5
Console.WriteLine("Modified value inside ModifyByValue: " & value)
End Sub
Page 13 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
In this program:
• We declare a variable num and initialize it with the value 10.
• We call the ModifyByValue function, passing num by value (without using ByRef).
• Inside the function, we modify the local copy of the value (not affecting the original num
variable).
• When we print the value of num after the function call, it remains unchanged at 10.
➢ When procedures or functions are called, the parameters or arguments (the values passed to
the procedure or function) must be in the same order as the parameters in the declaration
in
header and each argument must be of the same type as the parameter given in the header.
st
In brief: u
A procedure with no parameters is defined as follows:
PROCEDURE <identifier>
g
<statements>
ENDPROCEDURE
u
A procedure with parameters is defined as follows:
A
PROCEDURE <identifier>(<param1>:<datatype>, <param2>:<datatype>...)
<statements>
r.
ENDPROCEDURE
M
The <identifier> is the identifier used to call the procedure. Where used, param1, param2,
etc. are identifiers for the parameters of the procedure. These will be used as variables in the
statements of the procedure.
Procedures should be called as follows:
CALL <identifier>
CALL <identifier>(Value1,Value2...)
When parameters are used, Value1, Value2... must be of the correct data type as in the
definition of the procedure.
Page 14 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
When the procedure is called, control is passed to the procedure. If there are any parameters, these
are substituted by their values, and the statements in the procedure are executed. Control is then
returned to the line that follows the procedure call.
Example – use of procedures with and without parameters
PROCEDURE DefaultLine
CALL LINE(60)
ENDPROCEDURE
in
PROCEDURE Line(Size : INTEGER)
DECLARE Length : INTEGER
FOR Length ← 1 TO Size
OUTPUT '-'
st
NEXT Length
ENDPROCEDURE
IF MySize = Default
u
THEN
g
CALL DefaultLine
ELSE
u
CALL Line(MySize)
ENDIF
A
r.
A function with no parameters is defined as follows:
FUNCTION <identifier> RETURNS <data type>
M
<statements>
ENDFUNCTION
A function with parameters is defined as follows:
FUNCTION <identifier>(<param1>:<datatype>, <param2>:<datatype>...) RETURNS
<data type>
<statements>
ENDFUNCTION
Page 15 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
The keyword CALL should not be used when calling a function. Functions should only be called as
part of an expression.
When the RETURN statement is executed, the value returned replaces the function call in the
expression and the expression is then evaluated.
Example – definition and use of a function
FUNCTION SumSquare(Number1:INTEGER, Number2:INTEGER) RETURNS INTEGER
RETURN Number1 * Number1 + Number2 * Number2
ENDFUNCTION
in
OUTPUT "Sum of squares = ", SumSquare(10, 20)
st
u
g
u
A
r.
M
References: Coursebooks (Watson & Williams; Lawrey; Piper; Morgan)
Page 16 of 16