Application programming 1 assignment
Using an example (program e.g. division by zero)
discuss exception handling in visual studio
Slide 6- 1
Procedures and Functions
Revision Question
(i) Write a function procedure that computes the
perimeter of a rectangle.
(ii) Write a procedure that makes use of the
function above to calculate the perimeter of a
rectangle.
Slide 6- 3
Introduction
A procedure is a collection of statements that
performs a task
Event handlers are a type of procedure
A function is a collection of statements that
performs a task and returns a value to the VB
statement that executed it
Functions work like intrinsic functions, such as
Inputbox()
A method can be either a procedure or a
function
Procedures
1
You Can Write Your Own General Purpose
Procedures That Perform Specific Tasks
General Purpose Procedures Are Not Triggered
by Events but Called From Statements in Other
Procedures
Procedures
A moderately complex program needs to perform multiple tasks.
A procedure is a block of program code that performs a specific
task.
A program can be considered as the assembly of multiple
procedures.
Execution of a procedure is commonly referred to as calling a
procedure.
Most Visual Basic procedures are Sub procedures and Function
procedures.
How Procedure Works
A (called) procedure is invoked by another procedure (caller).
The called procedure does the job and return the result to the
caller or simply transfer control to the caller without returning
anything.
An analogy of procedure calls:
boss
worker1 worker2 worker3
worker4 worker5
Sub Procedures vs. Function
Procedures
A Sub procedure does not return a value after
performing its assigned task.
A Function procedure returns a value after
performing its assigned task. A Function
procedure can only return one value.
Sub Procedures
Two types of Sub procedures:
1. Event procedures
- Associated with a specific object and event
2. General Purpose Sub procedures
- Independent of any object and event; can be
called (or invoked) from one or more places
in an application.
Procedure Uses
An event handler is a type of procedure
Automatically executed when an event such as a
mouse click occurs
General purpose procedures are triggered (called )
by statements in other procedures, not by events
Procedures help simplify & modularize code by:
Breaking it into small, manageable pieces
Performing a task that is needed repeatedly
Dividing a program into a set of logical tasks
Declaring a Procedure
[AccessSpecifier] Sub ProcedureName ([ParameterList])
[Statements]
End Sub
AccessSpecifier is optional and establishes
accessibility to the program
Sub and End are keywords
ProcedureName used to refer to procedure
Use Pascal casing, capitalize 1st character of
the name and each new word in the name
ParameterList is a list of variables or values
being passed to the sub procedure
More on the Access Specifier
Private allows use only from that form
Public allows use from other forms
If not specified, default is Public
There are other access specifiers such as:
Protected
Friend
Protected Friend
These will be discussed in later
Sample Procedure,
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
ListBox1.Items.Add("Hello am on the form")
ListBox1.Items.Add(" ")
DisplayMessage()
ListBox1.Items.Add("execution is back to Form1")
End Sub
Private Sub DisplayMessage()
ListBox1.Items.Add("Hello am from the DisplayMessage procedure")
ListBox1.Items.Add(" ")
End Sub
Private Sub bntExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
bntExit.Click
Me.Close()
End Sub
End Class
Slide 6- 13
Private sub arearec (ByVal L as integer, ByVal W as
integer )
dim area as integer
L=10
W= 5
area = L*W
Return….
End sub
Slide 6- 14
Public Class Form1
Private Sub bntSub_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles bntSub.Click
addNumbers()
MsgBox("Excution back to the bntSub _click")
End Sub
Returns to Calls addNumbers
btnSub_Click Private Sub addNumbers() procedure
Dim num1 As Integer = 23354
Dim num2 As Integer = 236328
MsgBox(num1 + num2)
End Sub
End Class
Slide 6- 16
Passing Arguments to a
2 Procedure
areaRec(10,5)
When calling a procedure, you can
pass it values known as arguments
Arguments
Argument – a value passed to a procedure
We’ve already done this with functions
Value = inputbox(“5”)
Calls the inputbox function and passes “5” as
an argument
A procedure must be declared with a parameter
list in order to accept an argument
Passing Variables
5 12
A variable has both a value and a unique address in the
computer's memory. Either the value or the address
can be passed to a Sub procedure.
Two ways of passing parameters:
(1) Pass by value: The value of the variable is passed to
the called procedure;
(2) Pass by reference: The address of the variable is
passed to the called procedure.
Two analogies
Telling someone the balance of your banking account
passes the information about your banking account.
This is equivalent to "pass by value".
Giving someone the information on the account
number, PIN, etc. authorizes the person to deposit or
withdraw from the account, as well as to query the
balance. This equivalent to "pass by reference".
What is the major difference between the two?
ByVal or ByRef Argument Example
Public Class Form1
Function TestByref(ByVal N As Integer) As Integer
N = 0
Return N
End Function
Function TestByVal(ByRef N As Integer) As Integer
N = 0
Return N
End Function
Private Sub bntByRef_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
bntByRef.Click
Dim K As Integer
K = 100
TestByref(K)
MsgBox("(ByRef)The value of K is :" & K)
End Sub
Private Sub bntByVal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
bntByVal.Click
Dim K As Integer
K = 100
TestByVal(K)
MsgBox("(ByVal)The value of K is :" & K)
End Sub
End Class
Passing Arguments By Value
DisplayValue(5) ‘calls DisplayValue procedure
Sub DisplayValue(ByVal intNumber As Integer)
' This procedure displays a value in a message box.
MessageBox.Show(intNumber.ToString)
End Sub
intNumber declared as an integer argument
Storage location intNumber created by procedure
A value, 5 in this case, must be supplied and is
copied into the storage location for intNumber
The DisplayValue procedure then executes
Passing Multiple Arguments
ShowSum(intValue1, intValue2) ‘calls ShowSum procedure
Sub ShowSum(ByVal intNum1 As Integer, _
ByVal intNum2 As Integer)
' This procedure accepts two arguments, and prints
' their sum on the form.
Dim intSum As Integer
intSum = intNum1 + intNum2
MessageBox.Show("The sum is " & intSum.ToString)
End Sub
Multiple arguments separated by commas
Value of first argument is copied to first
Second to second, etc.
Example of Passing Arguments By
Value
Public Class Form1
Private Sub addProcedure(ByVal a As Integer, ByVal b As
Integer)
Dim sum As Integer
sum = a + b
MessageBox.Show("the sum of a and b is :" & sum)
End Sub
Private Sub Button1_Click(sender As System.Object, e As
System.EventArgs) Handles Button1.Click
addProcedure(23, 23)
End Sub
End Class
Slide 6- 24
Passing Arguments ByVal or ByRef
Arguments are usually passed ByVal
New storage location created for procedure
Storage location gets a copy of the value
Any changes in value are made to the copy
Calling procedure won’t “see” the changes
Arguments can also be passed ByRef
Procedure points to (references) argument’s original
storage location
Any changes are made to the original value
Calling procedure “sees” the changes
Demonstrate this through an example
Functions
3
A Function Returns a Value to the
Part of the Program That Called the
Function
Declaring a Function
[AccessSpecifier] Function FunctionName
([ParameterList]) _
As DataType
[Statements]
Return value
End Function
Private Function addnumbers (ByVal num1 as integer,
ByVal num2 as integer)as integer
Dim sum as integer
Sum = num1 + num2
Return sum
End function
New keyword Function
Also new is As DataType which states the data
type of the value to be returned
Return value is specified in a Return expression
Function Call Example
sngTotal = Sum(sngValue1, sngValue2)
Function Sum(ByVal sngNum1 As Single, _
ByVal sngNum2 As Single) As Single
Dim sngResult As Single
sngResult = sngNum1 + sngNum2
Return sngResult
End Function
sngValue1 & sngValue2 must be data type Single
Data types must agree with parameter list
sngTotal must be Single, agrees with return value
Example of a function that add two
numbers and returns the sum
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As
System.EventArgs) Handles Button1.Click
Dim results As Integer
results = addnumbers(3, 23)
MessageBox.Show(" the sum of a and be is :" & results)
End Sub
Private Function addnumbers(ByVal a As Integer, ByVal b As Integer) As
Integer
Dim sum As Integer
sum = a + b
Return sum
End Function
End Class
Slide 6- 29
Summary
Procedures
The declaration for a procedure begins with a Sub statement and ends
with an End Sub statement. The code that appears between these two
statements is the body of the procedure.
When a procedure call executes, the application branches to that
procedure and executes its statements. When the procedure has finished,
the application branches
Passing Arguments to Procedures
A parameter is a special variable that receives an argument value
passed into a procedure or function. If a procedure or function has a
parameter, you must supply an argument when calling the procedure or
function.
• When a procedure or function with multiple parameters is called,
arguments are assigned to the parameters in left-to-right order.
Summary
There are two ways to pass an argument to a procedure: by value or
reference. Passing an argument by value means that only a copy of
the argument is passed to the procedure. Because the procedure has
only a copy, it cannot make changes to the original argument.
When an argument is passed by reference, however, the procedure
has access to the original argument and can make changes to it.
Functions
• A function returns a value to the part of the program that called it.
Similar to a procedure, it is a set of statements that perform a task
when the function is called.
• A value is returned from a function by the Return statement
Revision Questions
Describe the difference between:
Passing ByVal and paasing ByRef
Sub procedure and a Function procedure
Write a function procedure that computes the
perimeter of a rectangle.
Write a procedure that makes use of the function
above to calculate the perimeter of a rectangle
Public Class Form1
Private Sub DisplayValue(ByVal i As Integer)
i = 0
MsgBox("The value of i is:" & i)
End Sub
Private Sub bntByval_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles bntByval.Click
Dim n As Integer
n = 10
DisplayValue(n)
MsgBox("Execution back to the bntByval_click procedure")
MsgBox("The value of n is:" & n)
End Sub
End Class
Public Class Form1
Private Sub addNumbers()
Dim sum As Integer
Dim Num1, Num2 As Integer
Num1 = 20
Num2 = 20
sum = Num1 + Num2
MsgBox(sum)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles Button1.Click
addNumbers()
End Sub
End Class
ByVal ByRef
Public Class Form1
Private Sub DisplayValue(ByRef i As Integer)
i = 0
MsgBox("The value of i is:" & i)
End Sub
Private Sub bntByval_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles bntByval.Click
Dim n As Integer
n = 10
DisplayValue(n)
MsgBox("Execution back to the bntByval_click procedure")
MsgBox("The value of n is:" & n)
End Sub
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
End Sub
Dim myArray() = {5, 7, 8, 9}
Private Sub bntAddAll_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles bntAddAll.Click
Try
For i = 0 To 4
lstAdd.Items.Add(myArray(i))
Next
Catch ex As Exception
MsgBox("an error has occured " & Environment.NewLine & ex.ToString)
Finally
MsgBox("This is the finally")
Beep()
End Try
End Sub
End Class