Chapter 8 Procedures - Functions
Chapter 8 Procedures - Functions
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.
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:
Page 1 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
Procedures
A procedure runs the code inside it, and does not return a value. The structure of a procedure is:
PROCEDURE identifier()
END PROCEDURE
in
The identifier is then used in the main program.
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
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()
INPUT Numl
u
OUTPUT ("Enter a second number")
g
INPUT Num2
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
Sub multiply()
Dim numl, num2, total As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine()
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.
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
Example 1
M
Write a function to ask the user to enter two values, add them together and return the
value:
FUNCTION Multiply()
INPUT Numl
INPUT Num2
ENDFUNCTION
Page 4 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
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()
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
NEXT X
r.
RETURN Total
END FUNCTION
M
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()
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
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.
Code to run
END PROCEDURE
in
or
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:
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
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
outputNumbers(firstNumber, secondNumber)
End Sub
Page 9 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
➢ Function
Example: Design a function that takes the radius of a circle as a parameter and returns the area of
that circle.
in
Incoming
parameters
End Function
End of the
st
function
Solution
A
INPUT Radius
Area ← Circle(Radius)
M
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
in
End Function
End Module
st
It is also possible to use the returned value directly in the Console.Writeline command:
Sub Main()
➢ Procedure
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.
Passing by value
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.
<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
CALL celsius(myTemp)
r.
VB Syntax:
Sub celsius(ByVal temperature As Decimal)
M
Page 12 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
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
Page 13 of 16
O & A Level Computer Science P2/P4 Procedures & Functions N.A
In this program:
➢ 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
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.
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.
PROCEDURE DefaultLine
CALL LINE(60)
ENDPROCEDURE
in
PROCEDURE Line(Size : INTEGER)
OUTPUT '-'
st
NEXT Length
ENDPROCEDURE
IF MySize = Default
u
THEN
g
CALL DefaultLine
ELSE
u
CALL Line(MySize)
ENDIF
A
r.
<statements>
ENDFUNCTION
<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.
in
OUTPUT "Sum of squares = ", SumSquare(10, 20)
st
u
g
u
A
r.
M
Page 16 of 16