1
INF110Visual Basic Programming
AUBG Fall semester 2009
Reference books:Schneider D., An Introduction to Programming Using Visual Basic, Prentice Hall, Pearson Education Inc., 7th Ed. 2008, 6th Ed. 2006 Liberty J., Learning Visual Basic .NET, O’Reilly, 2002 Any Visual Basic book available in AUBG library
Course lecturer: Assoc. Prof. Svetla Boytcheva PhD
2
INF110 Visual Basic Programming AUBG Spring semester 2011
Lecture 10Title:
Visual Basic(Procedures1: Sub-s &
Function-s)
3
Lecture Contents:Introducing the procedures conceptAdvantages of using proceduresSub procedureFunction procedureData exchange btw proceduresParameter passing mechanism
Actual arguments Formal parameters
4
Procedures Procedures
(Sub-s and (Sub-s and Function-s)Function-s)
INF110
Visual Basic Programming
5
The problem to be solved:The problem to be solved:To compute a Pythagorean triple using two integers m and To compute a Pythagorean triple using two integers m and
n (m>n) as input and applying following formulas to n (m>n) as input and applying following formulas to compute all the three sides of a right triangle:compute all the three sides of a right triangle:
side1 = mside1 = m22–n–n22 side2 = 2*m*nside2 = 2*m*n hypotenuse = mhypotenuse = m22+n+n22
Problem specification:Problem specification:
Input:Input: Two integers: m, nTwo integers: m, n
Output: Three values: side1, side2, hypotenuseOutput: Three values: side1, side2, hypotenuse
Process: Formulas providedProcess: Formulas provided
6
The problem to be solved:The problem to be solved:To compute 3 Pythagorean triples using two integers m and To compute 3 Pythagorean triples using two integers m and
n (m>n) as input and applying following formulas to n (m>n) as input and applying following formulas to compute all the three sides of a right triangle:compute all the three sides of a right triangle:
side1 = mside1 = m22–n–n22 side2 = 2*m*nside2 = 2*m*n hypotenuse = mhypotenuse = m22+n+n22
Problem specification:Problem specification:
Input:Input: Two integers: m, nTwo integers: m, n
Output: Three values: side1, side2, hypotenuseOutput: Three values: side1, side2, hypotenuse
Process: Formulas providedProcess: Formulas provided
Introduction to Sub Procedures
7
The problem to be solved:The problem to be solved:To compute 3 Pythagorean triples using two integers m and To compute 3 Pythagorean triples using two integers m and
n (m>n) as input and applying following formulas to n (m>n) as input and applying following formulas to compute all the three sides of a right triangle:compute all the three sides of a right triangle:
side1 = mside1 = m22–n–n22 side2 = 2*m*nside2 = 2*m*n hypotenuse = mhypotenuse = m22+n+n22
How to solve the problem?How to solve the problem? There exist many (at least 3) There exist many (at least 3) different approaches:different approaches:
• Duplicating 3 times solving code – bad solutionDuplicating 3 times solving code – bad solution
• Using repetition control structure – better solutionUsing repetition control structure – better solution
• Using a procedure as a separate independent Using a procedure as a separate independent program unit – the best solutionprogram unit – the best solution
Introduction to Sub Procedures
8
Module Module1Module Module1
Sub Main()Sub Main()
Dim m, n As IntegerDim m, n As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())
Side1 = m*m - n*nSide1 = m*m - n*n Side2 = 2*m*nSide2 = 2*m*n Hypotenuse = m*m + n*nHypotenuse = m*m + n*n
Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)
End SubEnd Sub
End ModuleEnd Module
Duplicating code solution
9
Source code in red has to be duplicated 3 times in order to solve the Source code in red has to be duplicated 3 times in order to solve the problemproblem
Module Module1Module Module1
Sub Main()Sub Main() Dim m, n As IntegerDim m, n As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())
Side1 = m*m - n*nSide1 = m*m - n*n Side2 = 2*m*nSide2 = 2*m*n
Hypotenuse = m*m + n*nHypotenuse = m*m + n*n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)
End SubEnd Sub
End ModuleEnd Module
Duplicating code solution
10
Source code after being duplicated 3 times in order to solve the problemSource code after being duplicated 3 times in order to solve the problem
Module Module1Module Module1
Sub Main()Sub Main() Dim m, n As IntegerDim m, n As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m*m - n*nSide1 = m*m - n*n Side2 = 2*m*nSide2 = 2*m*n Hypotenuse = m*m + n*nHypotenuse = m*m + n*n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)
Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m*m - n*nSide1 = m*m - n*n Side2 = 2*m*nSide2 = 2*m*n Hypotenuse = m*m + n*nHypotenuse = m*m + n*n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)
Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m*m - n*nSide1 = m*m - n*n Side2 = 2*m*nSide2 = 2*m*n Hypotenuse = m*m + n*nHypotenuse = m*m + n*n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)
End SubEnd Sub
End ModuleEnd Module
Duplicating code solution
11
The user or the developer may be asked to computeThe user or the developer may be asked to compute5, 10, 25 or more Pythagorean triples5, 10, 25 or more Pythagorean triples
Obviously, the solution must not be based on duplicatingObviously, the solution must not be based on duplicating codecode
We can use the repetition control structure(s) likeWe can use the repetition control structure(s) likeFor … NextFor … NextDo While (condition) … LoopDo While (condition) … LoopDo … Loop Until (condition)Do … Loop Until (condition)
And other modifications of loop statements from VBAnd other modifications of loop statements from VB
Using repetition control structure – better solution
12
Module Module1Module Module1 Sub Main()Sub Main() Dim m, n, counter As IntegerDim m, n, counter As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
For counter = 1 To For counter = 1 To 33 Step 1 Step 1 Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m * m - n * nSide1 = m * m - n * n Side2 = 2 * m * nSide2 = 2 * m * n Hypotenuse = m * m + n * nHypotenuse = m * m + n * n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse) Next counterNext counter
End SubEnd SubEnd ModuleEnd Module
Using repetition control structure – better solution
13
Module Module1Module Module1 Sub Main()Sub Main() Dim m, n, counter As IntegerDim m, n, counter As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
counter = 1counter = 1 Do While counter <= 3Do While counter <= 3 Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m * m - n * nSide1 = m * m - n * n Side2 = 2 * m * nSide2 = 2 * m * n Hypotenuse = m * m + n * nHypotenuse = m * m + n * n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse) counter = counter + 1counter = counter + 1 LoopLoop
End SubEnd SubEnd ModuleEnd Module
Using repetition control structure – better solution
14
Module Module1Module Module1 Sub Main()Sub Main() Dim m, n, counter As IntegerDim m, n, counter As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
counter = 1counter = 1 DoDo Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m * m - n * nSide1 = m * m - n * n Side2 = 2 * m * nSide2 = 2 * m * n Hypotenuse = m * m + n * nHypotenuse = m * m + n * n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse) counter = counter + 1counter = counter + 1 Loop Until counter = 3Loop Until counter = 3
End SubEnd SubEnd ModuleEnd Module
Using repetition control structure – better solution
15
The solution based on loop statements is better than the duplicating code The solution based on loop statements is better than the duplicating code but it but it keeps the same skeleton/structure of the console applicationkeeps the same skeleton/structure of the console application::
Module Module1Module Module1 Sub Main()Sub Main() . . .. . . End SubEnd SubEnd ModuleEnd Module
A better, more structured solution may be implemented using another A better, more structured solution may be implemented using another approach established as a corner stone in structured programming – all the approach established as a corner stone in structured programming – all the activities to solve a specific problem to be concentrated/encapsulated in a activities to solve a specific problem to be concentrated/encapsulated in a separate independent program unit - procedure. VB supports two types of separate independent program unit - procedure. VB supports two types of separate program units – subroutines separate program units – subroutines SubSub and functions and functions FunctionFunction..
Using a procedure – best solution
16
Applying this structured approach means a Applying this structured approach means a new skeleton/structure of the console application: The new procedure has to be defined/declared: The new procedure has to be defined/declared
Module Module1Module Module1 Sub Main()Sub Main() . . .. . . End SubEnd Sub
Sub PythagorTriple() . . . End Sub
End ModuleEnd Module
Using a procedure – best solution
17
Applying this structured approach means a new skeleton/structure of the Applying this structured approach means a new skeleton/structure of the console application: The new procedure has to be defined/declaredconsole application: The new procedure has to be defined/declared
Module Module1Module Module1 Sub Main()Sub Main() . . .. . . End SubEnd Sub
Sub PythagorTriple()Sub PythagorTriple() Dim m, n As IntegerDim m, n As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m * m - n * nSide1 = m * m - n * n Side2 = 2 * m * nSide2 = 2 * m * n Hypotenuse = m * m + n * nHypotenuse = m * m + n * n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)
End SubEnd Sub
End ModuleEnd Module
Using a procedure – best solution
18
After the procedure being specified, it may be called, activated, invoked 3, 5, After the procedure being specified, it may be called, activated, invoked 3, 5, 10, 15, 25, … as many times as the user needs using a calling statement 10, 15, 25, … as many times as the user needs using a calling statement typed in the caller /master/ unit. The procedure itself is called /slave/ unit.typed in the caller /master/ unit. The procedure itself is called /slave/ unit.
Module Module1Module Module1 Sub Main()Sub Main() . . .. . .
PythagorTriple()PythagorTriple() Call PythagorTriple()Call PythagorTriple()
PythagorTriple()PythagorTriple() . . . . . .
End SubEnd Sub
Sub PythagorTriple()Sub PythagorTriple() . . .. . . End SubEnd Sub
End ModuleEnd Module
Using a procedure – best solution
19
After the procedure being specified, it may be called, activated, invoked 3, 5, After the procedure being specified, it may be called, activated, invoked 3, 5, 10, 15, 25, … as many times as the user needs using a statement typed in 10, 15, 25, … as many times as the user needs using a statement typed in the calling /master/ unit. The procedure itself is called /slave/ unit.the calling /master/ unit. The procedure itself is called /slave/ unit.
Module Module1Module Module1 Sub Main()Sub Main() . . .. . .
PythagorTriple()PythagorTriple() :: Call PythagorTriple()Call PythagorTriple()PythagorTriple() PythagorTriple() :: PythagorTriple() PythagorTriple() :: PythagorTriple()PythagorTriple()
. . . . . . End SubEnd Sub
Sub PythagorTriple()Sub PythagorTriple() . . .. . . End SubEnd Sub
End ModuleEnd Module
Using a procedure – best solution
20
After the procedure being specified, it may be called, activated, invoked 3, 5, After the procedure being specified, it may be called, activated, invoked 3, 5, 10, 15, 25, … as many times as the user needs using a statement typed in 10, 15, 25, … as many times as the user needs using a statement typed in the calling /master/ unit. The procedure itself is called /slave/ unit.the calling /master/ unit. The procedure itself is called /slave/ unit.
Module Module1Module Module1 Sub Main()Sub Main() . . .. . .
PythagorTriple()PythagorTriple() . . . . . . End SubEnd Sub
Sub PythagorTriple()Sub PythagorTriple() . . .. . . End SubEnd Sub
End ModuleEnd Module
Using a procedure – best solution
21
After the procedure being specified, it may be called, activated, invoked 3, 5, After the procedure being specified, it may be called, activated, invoked 3, 5, 10, 15, 25, … as many times as the user needs using a statement typed in 10, 15, 25, … as many times as the user needs using a statement typed in the calling /master/ unit. The procedure itself is called /slave/ unit.the calling /master/ unit. The procedure itself is called /slave/ unit.
Module Module1Module Module1 Sub Main()Sub Main() . . .. . .
Dim counter As Integer = 1Dim counter As Integer = 1Do While counter <= 10Do While counter <= 10
PythagorTriple()PythagorTriple()counter = counter + 1counter = counter + 1
LoopLoop . . . . . . End SubEnd Sub
Sub PythagorTriple()Sub PythagorTriple() . . .. . . End SubEnd Sub
End ModuleEnd Module
Using a procedure – best solution
22
Module Module1Module Module1
Sub Main()Sub Main() PythagorTriple()PythagorTriple() Call PythagorTriple()Call PythagorTriple() End SubEnd Sub Sub PythagorTriple()Sub PythagorTriple() Dim m, n As IntegerDim m, n As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m * m - n * nSide1 = m * m - n * n Side2 = 2 * m * nSide2 = 2 * m * n Hypotenuse = m * m + n * nHypotenuse = m * m + n * n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse) End SubEnd Sub
End ModuleEnd Module
Using a procedure – best solutionEntire program source text
23
Sub PythagorTriple()Sub PythagorTriple() Dim m, n As IntegerDim m, n As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m * m - n * n Side2 = 2 * m * n Hypotenuse = m * m + n * n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse) End SubEnd Sub
The PythagorTriple() Sub procedure illustrates one primitive and restricted (but not the only The PythagorTriple() Sub procedure illustrates one primitive and restricted (but not the only possible) approach of solving a problem when all the I-P-O activities are encapsulated within the possible) approach of solving a problem when all the I-P-O activities are encapsulated within the procedure body:procedure body:
Input Data for m,n are typed (entered) at run time from the keyboard..Side1, Side2, Hypotenuse are evaluated through assignment statements..Output (result) data displayed on screen through Console.WriteLine()..
Using a procedure – best solutionAll I-P-O encapsulated inside
24
Ways to assign data for m,n:Ways to assign data for m,n:
1.1. InitializationInitializationDim m As Integer = 8, n As Integer = 6
2.2. AssignmentAssignmentDim m,n As Integer = 6 m = 8 : n = 6
3.3. Typing /reading/ data from the keyboard or from input fileTyping /reading/ data from the keyboard or from input file Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) n = CInt(Console.ReadLine())
• Data exchange btw procedures: Data exchange btw procedures: Caller/Master procedure sends data and Called/Slave procedure receives data sent by Master through parameter passing mechanism..See next slide for details.See next slide for details.
Using a procedure – best solutionData exchange btw procedures
Introduction to parameter passing mechanism
25
1.1. Data exchange btw procedures: Caller/Master procedure sends data Data exchange btw procedures: Caller/Master procedure sends data and Called/Slave procedure receives data sent by Master through and Called/Slave procedure receives data sent by Master through parameter passing mechanism.parameter passing mechanism.
2.2. Data sent by Master is known as Data sent by Master is known as actual data and appears in the calling and appears in the calling statement as a statement as a list of actual arguments separated by comma. separated by comma.
3.3. Data received by Slave to be processed appears in the header/title of Data received by Slave to be processed appears in the header/title of the called procedure as a list of the called procedure as a list of formal parameters separated by separated by comma.comma.
4.4. The correspondence btw actual arguments and formal parameters by The correspondence btw actual arguments and formal parameters by number and data type is mustnumber and data type is must..
Using a procedure – best solutionData exchange btw procedures
Introduction to parameter passing mechanism
26
2.2. Data sent by Master is known as actual data and appears in the calling Data sent by Master is known as actual data and appears in the calling statement as a list of actual arguments separated by comma. statement as a list of actual arguments separated by comma.
The calling statementThe calling statementPythagorTriple()
Is to be replaced withIs to be replaced withPythagorTriple(8, 6)
oror
Dim Arg1 As Integer = 8, Arg2 As Integer = 6PythagorTriple(Arg1, Arg2)
oror
Dim Arg1, Arg2 As IntegerArg1 = 10 : Arg2 = 6PythagorTriple(Arg1+4*Arg2, Arg2-6 mod 3 *2)
Using a procedure – best solutionData exchange btw procedures
Introduction to parameter passing mechanism
27
3.3. Data received by Slave to be processed appears in the header/title of Data received by Slave to be processed appears in the header/title of the called procedure as a list of formal parameters separated by comma. the called procedure as a list of formal parameters separated by comma.
The non-parameter procedure bodyThe non-parameter procedure bodySub PythagorTriple()Sub PythagorTriple() Dim m, n As IntegerDim m, n As Integer Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (m>n):")Console.WriteLine("Enter 2 numbers m,n (m>n):") m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine())m = CInt(Console.ReadLine()) : n = CInt(Console.ReadLine()) Side1 = m * m - n * nSide1 = m * m - n * n Side2 = 2 * m * nSide2 = 2 * m * n Hypotenuse = m * m + n * nHypotenuse = m * m + n * n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)
End SubEnd Sub
Is to be replaced withIs to be replaced with
Using a procedure – best solutionData exchange btw procedures
Introduction to parameter passing mechanism
28
Sub PythagorTriple(Sub PythagorTriple(m As Integer, n As Integer)m As Integer, n As Integer) Dim Side1, Side2, Hypotenuse As IntegerDim Side1, Side2, Hypotenuse As Integer
Side1 = Side1 = mm * * mm - - nn * * nn Side2 = 2 * Side2 = 2 * mm * * nn Hypotenuse = Hypotenuse = mm * * mm + + nn * * nn
Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse)
End SubEnd Sub
Using a procedure – best solutionData exchange btw procedures
Introduction to parameter passing mechanism
29
Devices for modularity
• VB.NET has two constructs for dividing problems into smaller pieces (sub-problems)
– Sub procedures
– Function procedures
– Some people call them methods
They are blocks of code that can be referred to by a name.
- Rather like having a program within a program
30
Sub Procedures and Function Procedures
- Allow removal of duplicated code within the same program – just write block of code once and refer to it from anywhere in the program
- Leads to better structured programming
- Well-designed procedures and functions can be reused in other applications
- Needs to be stand-alone code
- The only link to the rest of the program is through parameters – data sent to the block of code.
- Needs to have a specific functionalitye.g. calculating some quantity
31
Sub Procedures and Function Procedures
- Two activities are must for effective processing with Sub Procedures and Function Procedures in VB:
- 1. Sub Procedures and Function Procedures are to be declared or defined or described in the source text of the program (it happens once only)
- 2. Sub Procedures and Function Procedures are to be called or activated (it may happen more than once)
32
Sub-procedures (or just Subs) and Functions (or more precisely Function procedures) may be invoked (or called) any number of times.
33
The two coming slides present whatB.Kernighan and D.Ritchie think on
functions in C
It’s absolutely valid for both types of procedures (Sub and Function) in
Visual Basic
34
Basics of procedures:
“Properly designed functions permit to ignore how a job’s done. Knowing what is done is sufficient.”
B.Kernighan & D.Ritchie
Most important reasons to use procedures:
1. Dividing a program into procedures is one of the major principles of structured programming.
2. Using procedures results in reduced program size.
35
Basics of procedures:
“A function provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation. ”
B.Kernighan & D.Ritchie
Usually procedures are specified to be called many times.
You can see often a short procedure defined and called only once, just because it clarifies some piece of code.
36
Sub Procedures
• Performs one or more related tasks
• General syntax
Sub ProcedureName()
block of code – VB statements
End Sub
37
Sub Procedure Structure
Sub SubName()
declarations
statements
End Sub
Statements perform the “function”of the sub procedure
local declarations – “private”to the sub procedure
sub-procedure name
38
Naming Sub procedures
• The rules for naming Sub procedures are the same as the rules for naming variables.
39
Example
Sub Squares10()
Dim Num As Integer Dim NumSquared As Integer For Num = 1 To 10 NumSquared = Num*Num Console.Writeline(NumSquared) Next Num
End Sub
The statements to display the squares of the first ten numbers written as a Sub procedure
40
Calling a Sub Procedure
In order to invoke a sub procedure, i.e. to get its statements executed, the sub procedure must be called from wherever in the program its functionality is needed.
When a sub procedure is called, the current sequence of statement execution is temporally suspended, and the statements of the sub procedure are executed instead.
When the sub procedure statements are completed, a return is made to the previous sequence of statement execution.
To invoke or call a sub procedure, its name must be written, e.g. ProcedureName()
41
Calling a Sub procedure
• The statement that invokes a Sub procedure is also referred to as a call statement
• A call statement looks like this
Call ProcedureName()
Or just
ProcedureName() - Call is optional
Calling a sub procedure is effectively an unconditional branch in the code.
42
Sub Gaga()
Example
...Gaga()...
...
...
End Sub
Call Sub Gaga
Return from Sub Gaga- a return is made to the statementfollowing the Call
A sub procedure is called bynaming it in a statement. Note the brackets
Sub procedure code
43
Module Module1
Sub Main()
End Sub
End Module
You may not be aware of it, but we have been using the Sub procedure Main in our programs already.
44
Example
Console.Writeline(variable)
The system Sub procedure Console.Writeline() displays the value of a variable.
45
Module Module1
Sub Main()ShowMessage()Console.WriteLine(“Press Enter”)Console.ReadLine()
End Sub
Sub ShowMessage()Console.WriteLine(“Greetings”)
End Sub
End Module
Note that user-defined procedures come after Sub Main()
46
It is possible for one sub procedure to call another, and so on.
Effectively, we have a number of nested Sub calls.
47
Sub Procedures Calling Other Sub Procedures
Sub Gaga() ... FirstPart()End Sub
Sub FirstPart() SecondPart()End Sub
Sub SecondPart() ...End Sub
48
Data exchange among procedures
Calling or Caller or Master procedureAnd
Called or Slave procedure
The Master procedure sends data to Slave procedure via actual arguments.The Slave procedure receives data coming from Master via formal parameters.
The actual_arguments/formal_parameters correspondence
Adding Parameters
49
The power and versatility of a Sub may be increased by using parameters.
A parameter acts as “placeholder” for a value (of data) that you want to “pass” to the Sub.
Parameters are placed within the parentheses of the Sub declaration
Sub SubName()
Adding Parameters
50
Passing Data to Sub Procedure
• You can send items to a Sub procedure
Sum(2, 3)
Sub Sum(Num1 As Integer, Num2 As Integer)
• In the Sum Sub procedure, 2 will be stored in Num1 and 3 will be stored in Num2
• Num1 and Num2 are variables that are automatically available in the Sub procedure
51
Parameters and Arguments
CalculateDensity("Alaska", 627000, 591000)
Arguments – what you send to a Sub procedure
Parameters – place holders for what the sub procedure
receives
Sub CalculateDensity(state As String, _
pop As Double, _
area As Double)
52
= actual data
53
The parameters acts as extra local variables
- they may be accessed within the Sub
E.g.
Sub FindGreaterNum(Num1 As Integer, Num2 As Integer)
If Num1 > Num2 ThenConsole.Writeline(“Num1 is greater”)
ElseConsole.Writeline(“Num2 is greater”)
EndIf
End Sub
54
Module Module1
Sub Main()ShowMessage(“Greetings”)Console.WriteLine(“Press Enter”)Console.ReadLine()
End Sub
Sub ShowMessage(Text As String)Console.WriteLine(Text)
End Sub
End Module
55
Module Module1
Sub Main()ShowMessage(“Greetings”, 3)Console.WriteLine(“Press Enter”)Console.ReadLine()
End Sub
Sub ShowMessage(Text As String, Times as Integer)Dim Index As IntegerFor Index = 1 To Times
Console.WriteLine(Text)Next Index
End Sub
End Module
56
Sub-Procedure Structure
Sub SubName(Parameter1, Parameter2, ...)
declarations
statements
End Sub
Parameters must be declared using the format
Variable_Name As Data_Type
57
Parameter Passing by Value
• Keyword ByVal stands for “By Value”
• ByVal actual arguments retain their original value after Sub procedure terminates
Formal parameters must be declared using the format
ByVal Variable_Name As Data_Type
58
Parameter Passing by Reference
• ByRef stands for “By Reference”
• ByRef actual arguments can be changed by the Sub procedure and retain the new value after the Sub procedure terminates
Formal parameters must be declared using the format
ByRef Variable_Name As Data_Type
59
Local Variables
• These are variables declared inside a Sub procedure with a Dim statement
• Space reserved in memory for these variables until the End Sub – then the variables cease to exist
60
Class-Level Variables
• Visible to every procedure in a Form’s code without being passed
• Dim statements for Class-Level variables are placed
– Outside all procedures– At the top of the program (or class) region
61
Scope
• Class-level variables have class-level scope and are available to all procedures in the class
• Variables declared inside a procedure have local scope and are only available to the procedure in which they are declared
62
Debugging
• Programs with Sub procedures are easier to debug
• Each Sub procedure can be checked individually before being placed into the program
63
Intro to Function procedures
A “special” property of the Sub-procedure is that it does not return a “result” (value).
All the job is done within the Sub-procedure. The only activity performed when the Sub-procedure completes (exits, terminates) is to transfer the control back to the Master unit. No data returned (transferred) back to the Calling unit.
The Function procedure (to be described next), on the other hand does return a result.
64
Intro to Function procedures
The problem to be solved:The problem to be solved:To compute the area of a circle using a Function procedure:To compute the area of a circle using a Function procedure:
area = 3.14 * radius * radiusarea = 3.14 * radius * radius
Problem specification:Problem specification:
Input:Input: One real value: radiusOne real value: radius
Output: one result value: the area of a circleOutput: one result value: the area of a circle
Process: Formula provided: area = 3.14 * radius * radiusProcess: Formula provided: area = 3.14 * radius * radius
65
Intro to Function procedures
The problem to be solved:The problem to be solved:To compute the area of a circle using a Function procedure:To compute the area of a circle using a Function procedure:
area = 3.14 * radius * radiusarea = 3.14 * radius * radius
How to solve the problem?How to solve the problem? There exist many (at least 2) There exist many (at least 2) different approaches:different approaches:
• Writing all the code in sub Main() – bad solutionWriting all the code in sub Main() – bad solution
• Using a Function procedure as a separate independent Using a Function procedure as a separate independent program unit – the best solutionprogram unit – the best solution
66
Module Module1Module Module1
Sub Main()Sub Main()
Dim Dim radius, arearadius, area As As SingleSingle Const PI Const PI As As Single = 3.14Single = 3.14
Console.WriteLine("Enter Console.WriteLine("Enter real real numbernumber a as s radiusradius:"):") radius radius = Console.ReadLine()= Console.ReadLine()
area = PI * radius * radiusarea = PI * radius * radius Console.WriteLine("Result is {0}", Console.WriteLine("Result is {0}", areaarea))
End SubEnd Sub
End ModuleEnd Module
All the code in Sub Main()
67
1.1. Data exchange btw procedures: Data exchange btw procedures:
2.2. Result value generated within the Called/Slave procedure.Result value generated within the Called/Slave procedure.
3.3. Result value generated within the Called/Slave procedure to be Result value generated within the Called/Slave procedure to be transferred to Calling/Caller/Master procedure using one of the following transferred to Calling/Caller/Master procedure using one of the following two ways:two ways:1.1. Through return statementThrough return statement2.2. Through the procedure nameThrough the procedure name
4.4. One only value may be transferred following the steps above.One only value may be transferred following the steps above.
5.5. Result including >1 values may be transferred to Caller/Master Result including >1 values may be transferred to Caller/Master procedure through the procedure through the ByRefByRef type of formal parameters. type of formal parameters.
Using a Function procedure
68
Module Module1Module Module1
Sub Main()Sub Main() Console.WriteLine(Area(10))Console.WriteLine(Area(10)) Dim x As Single = 20Dim x As Single = 20 Console.WriteLine(Area(x))Console.WriteLine(Area(x)) Console.WriteLine(Area(x + 2 * 5))Console.WriteLine(Area(x + 2 * 5)) End SubEnd Sub
Function Area(rad As Single) As SingleFunction Area(rad As Single) As SingleConst PI Const PI As As Single = 3.14Single = 3.14Dim result As SingleDim result As Singleresult = Pi * rad * radresult = Pi * rad * radreturn result
End FunctionEnd Function
End ModuleEnd Module
Using a Function procedure
69
Module Module1Module Module1
Sub Main()Sub Main() Console.WriteLine(Area(10))Console.WriteLine(Area(10)) Dim x As Single = 20Dim x As Single = 20 Console.WriteLine(Area(x))Console.WriteLine(Area(x)) Console.WriteLine(Area(x + 2 * 5))Console.WriteLine(Area(x + 2 * 5)) End SubEnd Sub
Function Area(rad As Single) As SingleFunction Area(rad As Single) As SingleConst PI Const PI As As Single = 3.14Single = 3.14return Pi * rad * rad
End FunctionEnd Function
End ModuleEnd Module
Using a Function procedure
70
Module Module1Module Module1
Sub Main()Sub Main() Console.WriteLine(Area(10))Console.WriteLine(Area(10)) Dim x As Single = 20Dim x As Single = 20 Console.WriteLine(Area(x))Console.WriteLine(Area(x)) Console.WriteLine(Area(x + 2 * 5))Console.WriteLine(Area(x + 2 * 5)) End SubEnd Sub
Function Area(rad As Single) As SingleFunction Area(rad As Single) As SingleConst PI Const PI As As Single = 3.14Single = 3.14Dim result As SingleDim result As Singleresult = Pi * rad * radresult = Pi * rad * radArea = result
End FunctionEnd Function
End ModuleEnd Module
Using a Function procedure
71
Module Module1Module Module1
Sub Main()Sub Main() Console.WriteLine(Area(10))Console.WriteLine(Area(10)) Dim x As Single = 20Dim x As Single = 20 Console.WriteLine(Area(x))Console.WriteLine(Area(x)) Console.WriteLine(Area(x + 2 * 5))Console.WriteLine(Area(x + 2 * 5)) End SubEnd Sub
Function Area(rad As Single) As SingleFunction Area(rad As Single) As SingleConst PI Const PI As As Single = 3.14Single = 3.14
Area = Pi * rad * rad End FunctionEnd Function
End ModuleEnd Module
Using a Function procedure
72
Functions
• Passes back a value to the calling procedure 1/4
• Calling statement (context version 1)
variable = funcname(arg1, arg2, etc)
• Function structure
Function funcname(param1 As type, param2 As type, etc) As type
statements
Return returnvalue
End Function
Returns a value
Return type
Note the assignment
73
Functions
• Passes back a value to the calling procedure 2/4
• Calling statement (context version 1)
variable = funcname(arg1, arg2, etc)
• Function structure
Function funcname(ByVal param1 As type, ByVal param2 As type, etc) As type
statements
Return returnvalue
End Function
Returns a value
Return type
Note the assignment
74
Functions
• Passes back a value to the calling procedure 3/4
• Calling statement (version 2)
WriteLine(funcname(arg1, arg2, etc))
• Function structure
Function funcname(ByValparam1 As type, ByVal param2 As type, etc) As type
statements
Return returnvalue
End Function
Returns a value
Return type
Note the call
75
Functions
• Passes back a value to the calling procedure 4/4
• Calling statement (version 2)
WriteLine(funcname(arg1, arg2, etc))
• Function structure
Function funcname(param1 As type, param2 As type, etc) As type
statements
Return returnvalue
End Function
Returns a value
Return type
Note the call
76
Sub/Function calling context
• How to call Sub procedure – context as a statement– PythagoreanTriple()– Call PythagoreanTriple()
• How to call Function procedure – context as an operand of an expression– variable = funcname(arg1, arg2)– WriteLine( funcname(arg1, arg2) )
77
Functions and Subs• Pass back >1 values to the calling procedure 1/1
Calling statementsvariable = funcname(arg1, arg2, etc)
subname(arg1, arg2, etc)
• Function structureFunction funcname(ByRef param1 As type, ByRef param2 As type, etc) As type statements
param1 = <expression> : param2 = <expression>
Return returnvalue
End Function
• Sub structureSub subname(ByRef param1 As type, ByRef param2 As type, etc) statements
param1 = <expression> : param2 = <expression>
End Sub
78
Reminder: Parameter Passing by Value
• Keyword ByVal stands for “By Value”
• ByVal actual arguments retain their original value after Sub procedure terminates
Formal parameters must be declared using the format
ByVal Variable_Name As Data_Type
79
Reminder: Parameter Passing by Reference
• ByRef stands for “By Reference”
• ByRef actual arguments can be changed by the Sub procedure and retain the new value after the Sub procedure terminates
Formal parameters must be declared using the format
ByRef Variable_Name As Data_Type
80
Function Procedures
• Procedure definition– Procedure header
• Keyword Function• Followed by function procedure name and
variable declaration– Parameter list - variables used only within
function procedure• Followed by return type
– Procedure Body– Return value– End Function
81
Example of calling a system defined function
aVariable = Console.ReadLine()
The system function Console.ReadLine() reads a value from the keyboard into some variable.
82
Example of calling a user defined function By Value
Sub Main()Dim Item1 As Integer = 20Dim Item2 As Integer = 4Dim Sum As Integer
Sum = Add(Item1, Item2)Console.WriteLine("{0}+{1}={2}", Sum, Item1, Item2)
End Sub
Function Add(P1 As Integer, P2 As Integer)As Integer
Return P1 + P2
End Function
83
Example of calling a user defined function By reference
Sub Main()Dim Item1 As Integer = 20Dim Item2 As Integer = 4Dim Sum, Dif, Mul, Div As Integer
Sum = Add(Item1, Item2, Dif, Mul, Div)Console.WriteLine("{0} {1} {2} {3}", Sum, Dif, Mul, Div)
End Sub
Function Add(p1 As Integer, p2 As Integer, _ByRef p3 As Integer, ByRef p4 As Integer,_ByRef p5 As Integer) As Integer
p3 = p1 – p2 : p4 = p1 * p2 : p5 = p1 / p2Return p1 + p2
End Function
84
Example of calling a user defined Sub By reference
Sub Main()Dim Item1 As Integer = 20Dim Item2 As Integer = 4Dim Sum, Dif, Mul, Div As Integer
UserSub(Item1, Item2, Sum, Dif, Mul, Div)Console.WriteLine("{0} {1} {2} {3}", Sum, Dif, Mul, Div)
End Sub
Sub UserSub(p1 As Integer, p2 As Integer, _ByRef p3 As Integer, ByRef p4 As Integer, _ ByRef p5 As Integer, ByRef p6 As Integer)
p3 = p1 – p2 : p4 = p1 * p2 p5 = p1 / p2 : p6 = P1 + P2
End Sub
85
Summary
Real-world applications need complex large programmes
The best way to develop and maintain such a large programme is to construct it from small, manageable parts such as Sub-s and Function-s (Divide and Conquer).
This is motivated by Manageable programme development systems
Software reusability - The ability to use existing procedures as building blocks for new programs.
Standardisation - Programs can be created from off-the-shelf standardized pieces that accomplish specific tasks.
Code readability - Procedure code can be executed from several locations but only written once.
86
A procedure is invoked by a procedure call, that specifies name and provides the necessary arguments.
When the called procedure completes its task, it returns control to the calling procedure. In some cases, it also returns a result to the caller.
87
Sub Procedures in VB
User-defined procedures in VB have the format:
Sub procedure-name(parameter-list) declarations and statements
End Sub
The procedure-name, can be any valid identifier and is used to call this Sub procedure within the program.
The parameter-list is a comma-separated declaration of the type and name of the parameters needed.
The declarations and statements in the definition form the procedure body, which contains VB code to perform actions, generally by manipulating or interacting with the passed parameters.
A procedure is called by giving its name followed by a list of arguments, one for each parameter in its header.
88
Function Procedures in VB
Function procedures are similar to Sub procedure except that functions return a value to the caller.
User-defined functions in VB have the format:
Function procedure-name(parameter-list) As return type
declarations and statements
End Function
The procedure-name, parameter-list, and declarations and statements are as before.The return type indicates the data type of the returned value.
89
Passing Arguments
ByVal
Sends a copy of the arguments value to a called procedure The called procedure cannot alter the original value of the arguments
ByRef
Send a reference indicating where the value is stored in memory The called procedure can alter the original value of the arguments
90
Exercise
• Create a program to test Squares10() Sub
91
Exercise
• Create a program to test ShowMessage() Sub procedure – Without parameter – “Greetings” to be
displayed– With one parameter – the string to be displayed– With two parameters – the string to be
displayed and number of times to display the string
92
Exercise
• Create a program to test Sum() Sub with two integer parameters
93
Exercise
• Create a program to test FindGreaterNum() Sub with two integer parameters
94
Exercise
• Create a program to test Add() Function with two integer parameters and return data type integer
95
Reminder
Next class: Quiz 3 (20 min)on
Loops and Procedures
/Sub-s and Function-s/
96
Questions?Questions?
97
Thank You For
Your Attention!