INF110 Visual 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, - PowerPoint PPT Presentation

Loading...

PPT – INF110 Visual 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, PowerPoint presentation | free to download - id: 6051f4-Y2ViM



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

INF110 Visual 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,

Description:

INF110 Visual Basic Programming AUBG Fall semester 2009 Reference books: Schneider D., An Introduction to Programming Using Visual Basic, Prentice Hall, Pearson ... – PowerPoint PPT presentation

Number of Views:681
Avg rating:3.0/5.0
Slides: 98
Provided by: Gudy
Learn more at: http://home.aubg.bg
Category:

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: INF110 Visual 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,


1
INF110Visual Basic ProgrammingAUBG Fall
semester 2009Reference booksSchneider 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, OReilly, 2002 Any Visual
Basic book available in AUBG libraryCourse
lecturer Assoc. Prof. Svetla Boytcheva PhD
2
INF110 Visual Basic Programming AUBG Spring
semester 2011
Lecture 10 Title Visual Basic (Procedures1
Sub-s Function-s)
3
Lecture Contents
  • Introducing the procedures concept
  • Advantages of using procedures
  • Sub procedure
  • Function procedure
  • Data exchange btw procedures
  • Parameter passing mechanism
  • Actual arguments
  • Formal parameters

4
INF110 Visual Basic Programming
Procedures (Sub-s and Function-s)
5
The problem to be solved To compute a
Pythagorean triple using two integers m and n
(mgtn) as input and applying following formulas to
compute all the three sides of a right
triangle side1 m2n2 side2 2mn hypotenuse
m2n2 Problem specification Input Two
integers m, n Output Three values side1,
side2, hypotenuse Process Formulas provided
6
Introduction to Sub Procedures
The problem to be solved To compute 3
Pythagorean triples using two integers m and n
(mgtn) as input and applying following formulas to
compute all the three sides of a right
triangle side1 m2n2 side2 2mn hypotenuse
m2n2 Problem specification Input Two
integers m, n Output Three values side1,
side2, hypotenuse Process Formulas provided
7
Introduction to Sub Procedures
  • The problem to be solved
  • To compute 3 Pythagorean triples using two
    integers m and n (mgtn) as input and applying
    following formulas to compute all the three sides
    of a right triangle
  • side1 m2n2 side2 2mn hypotenuse m2n2
  • How to solve the problem? There exist many (at
    least 3) different approaches
  • Duplicating 3 times solving code bad solution
  • Using repetition control structure better
    solution
  • Using a procedure as a separate independent
    program unit the best solution

8
Duplicating code solution
Module Module1 Sub Main() Dim m, n
As Integer Dim Side1, Side2, Hypotenuse
As Integer Console.WriteLine("Enter 2
numbers m,n (mgtn)") m
CInt(Console.ReadLine()) n CInt(Console.ReadLi
ne()) Side1 mm - nn Side2
2mn Hypotenuse mm nn
Console.WriteLine("Result is 0 1 2",
Side1, Side2, Hypotenuse) End Sub End Module
9
Duplicating code solution
Source code in red has to be duplicated 3 times
in order to solve the problem Module Module1
Sub Main() Dim m, n As Integer
Dim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (mgtn)")
m CInt(Console.ReadLine()) n
CInt(Console.ReadLine()) Side1 mm -
nn Side2 2mn Hypotenuse
mm nn Console.WriteLine("Result is
0 1 2", Side1, Side2, Hypotenuse)
End Sub End Module
10
Duplicating code solution
Source code after being duplicated 3 times in
order to solve the problem Module Module1
Sub Main() Dim m, n As Integer
Dim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n (mgtn)")
m CInt(Console.ReadLine()) n
CInt(Console.ReadLine()) Side1 mm -
nn Side2 2mn Hypotenuse
mm nn Console.WriteLine("Result is
0 1 2", Side1, Side2, Hypotenuse)
Console.WriteLine("Enter 2 numbers m,n (mgtn)")
m CInt(Console.ReadLine()) n
CInt(Console.ReadLine()) Side1 mm -
nn Side2 2mn Hypotenuse
mm nn Console.WriteLine("Result is
0 1 2", Side1, Side2, Hypotenuse)
Console.WriteLine("Enter 2 numbers m,n (mgtn)")
m CInt(Console.ReadLine()) n
CInt(Console.ReadLine()) Side1 mm -
nn Side2 2mn Hypotenuse
mm nn Console.WriteLine("Result is
0 1 2", Side1, Side2, Hypotenuse) End
Sub End Module
11
Using repetition control structure better
solution
The user or the developer may be asked to
compute 5, 10, 25 or more Pythagorean
triples Obviously, the solution must not be
based on duplicating code We can use the
repetition control structure(s) like For
Next Do While (condition) Loop Do Loop
Until (condition) And other modifications of loop
statements from VB
12
Using repetition control structure better
solution
Module Module1 Sub Main() Dim m, n,
counter As Integer Dim Side1, Side2,
Hypotenuse As Integer For counter 1 To
3 Step 1 Console.WriteLine("Enter 2
numbers m,n (mgtn)") m
CInt(Console.ReadLine()) n CInt(Console.ReadLi
ne()) Side1 m m - n n
Side2 2 m n Hypotenuse m
m n n Console.WriteLine("Result
is 0 1 2", Side1, Side2, Hypotenuse)
Next counter End Sub End Module
13
Using repetition control structure better
solution
Module Module1 Sub Main() Dim m, n,
counter As Integer Dim Side1, Side2,
Hypotenuse As Integer counter 1
Do While counter lt 3
Console.WriteLine("Enter 2 numbers m,n (mgtn)")
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) counter
counter 1 Loop End Sub End Module
14
Using repetition control structure better
solution
Module Module1 Sub Main() Dim m, n,
counter As Integer Dim Side1, Side2,
Hypotenuse As Integer counter 1
Do Console.WriteLine("Enter 2
numbers m,n (mgtn)") m
CInt(Console.ReadLine()) n CInt(Console.ReadLi
ne()) Side1 m m - n n
Side2 2 m n Hypotenuse m
m n n Console.WriteLine("Result
is 0 1 2", Side1, Side2, Hypotenuse)
counter counter 1 Loop Until
counter 3 End Sub End Module
15
Using a procedure best solution
The solution based on loop statements is better
than the duplicating code but it keeps the same
skeleton/structure of the console
application Module Module1 Sub Main()
. . . End Sub End Module A better, more
structured solution may be implemented using
another approach established as a corner stone in
structured programming all the activities to
solve a specific problem to be concentrated/encaps
ulated in a separate independent program unit -
procedure. VB supports two types of separate
program units subroutines Sub and functions
Function.
16
Using a procedure best solution
Applying this structured approach means a new
skeleton/structure of the console application
The new procedure has to be defined/declared Modu
le Module1 Sub Main() . . . End
Sub Sub PythagorTriple() . . .
End Sub End Module
17
Using a procedure best solution
Applying this structured approach means a new
skeleton/structure of the console application
The new procedure has to be defined/declared Modu
le Module1 Sub Main() . . . End
Sub Sub PythagorTriple() Dim m, n
As Integer Dim Side1, Side2, Hypotenuse
As Integer Console.WriteLine("Enter 2
numbers m,n (mgtn)") m
CInt(Console.ReadLine()) n CInt(Console.ReadLi
ne()) 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
Sub End Module
18
Using a procedure best solution
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 typed in the caller /master/ unit. The
procedure itself is called /slave/ unit. Module
Module1 Sub Main() . .
. PythagorTriple() Call
PythagorTriple() PythagorTriple() . . .
End Sub Sub PythagorTriple() . . .
End Sub End Module
19
Using a procedure best solution
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 the calling /master/ unit. The procedure
itself is called /slave/ unit. Module Module1
Sub Main() . . . PythagorTriple() Call
PythagorTriple() PythagorTriple()
PythagorTriple() PythagorTriple() . .
. End Sub Sub PythagorTriple()
. . . End Sub End Module
20
Using a procedure best solution
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 the calling /master/ unit. The procedure
itself is called /slave/ unit. Module Module1
Sub Main() . . . PythagorTriple()
. . . End Sub Sub PythagorTriple()
. . . End Sub End Module
21
Using a procedure best solution
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 the calling /master/ unit. The procedure
itself is called /slave/ unit. Module Module1
Sub Main() . . . Dim counter As Integer
1 Do While counter lt 10 PythagorTriple() c
ounter counter 1 Loop . . .
End Sub Sub PythagorTriple() . . .
End Sub End Module
22
Using a procedure best solution Entire program
source text
Module Module1 Sub Main()
PythagorTriple() Call PythagorTriple()
End Sub Sub PythagorTriple() Dim
m, n As Integer Dim Side1, Side2,
Hypotenuse As Integer Console.WriteLine("
Enter 2 numbers m,n (mgtn)") m
CInt(Console.ReadLine()) n CInt(Console.ReadLi
ne()) 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 Sub End Module
23
Using a procedure best solution All I-P-O
encapsulated inside
Sub PythagorTriple() Dim m, n As Integer
Dim Side1, Side2, Hypotenuse As Integer
Console.WriteLine("Enter 2 numbers m,n
(mgtn)") 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 Sub 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
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().
24
Using a procedure best solution Data exchange
btw procedures Introduction to parameter passing
mechanism
  • Ways to assign data for m,n
  • Initialization
  • Dim m As Integer 8, n As Integer 6
  • Assignment
  • Dim m,n As Integer 6
  • m 8 n 6
  • Typing /reading/ data from the keyboard or from
    input file
  • Console.WriteLine("Enter 2 numbers m,n
    (mgtn)")
  • m CInt(Console.ReadLine())
  • n CInt(Console.ReadLine())
  • 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.

25
Using a procedure best solution Data exchange
btw procedures Introduction to parameter passing
mechanism
  1. Data exchange btw procedures Caller/Master
    procedure sends data and Called/Slave procedure
    receives data sent by Master through parameter
    passing mechanism.
  2. Data sent by Master is known as actual data and
    appears in the calling statement as a list of
    actual arguments separated by comma.
  3. 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.
  4. The correspondence btw actual arguments and
    formal parameters by number and data type is must.

26
Using a procedure best solution Data exchange
btw procedures Introduction to parameter passing
mechanism
2. Data sent by Master is known as actual data
and appears in the calling statement as a list of
actual arguments separated by comma. The calling
statement PythagorTriple() Is to be replaced
with PythagorTriple(8, 6) or Dim Arg1 As
Integer 8, Arg2 As Integer 6 PythagorTriple(
Arg1, Arg2) or Dim Arg1, Arg2 As
Integer Arg1 10 Arg2 6 PythagorTriple(Ar
g14Arg2, Arg2-6 mod 3 2)
27
Using a procedure best solution Data exchange
btw procedures Introduction to parameter passing
mechanism
  • 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 non-parameter procedure body
  • Sub PythagorTriple()
  • Dim m, n As Integer
  • Dim Side1, Side2, Hypotenuse As Integer
  • Console.WriteLine("Enter 2 numbers m,n
    (mgtn)")
  • 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 Sub
  • Is to be replaced with

28
Using a procedure best solution Data exchange
btw procedures Introduction to parameter passing
mechanism
Sub PythagorTriple(m As Integer, n As Integer)
Dim Side1, Side2, Hypotenuse As Integer
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 Sub
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 CIts
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 jobs done. Knowing what is done is
    sufficient.
  • B.Kernighan D.Ritchie
  • Most important reasons to use procedures
  • Dividing a program into procedures is one of the
    major principles of structured programming.
  • 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

sub-procedure name
local declarations private to the sub
procedure
Statements perform the function of the sub
procedure
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
NumNum        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
A sub procedure is called by naming it in a
statement. Note the brackets
Example
...
Gaga()
Call Sub Gaga
...
Sub Gaga()
...
Sub procedure code
...
End Sub
Return from Sub Gaga - a return is made to the
statement following the Call
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() Cons
ole.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
Adding Parameters
Data exchange among procedures Calling or
Caller or Master procedure And 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_pa
rameters correspondence
49
Adding Parameters
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()
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
Arguments what you send to a Sub procedure
CalculateDensity("Alaska", 627000, 591000)
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 gt Num2 Then Console.Writeline
(Num1 is greater) Else Console.Writeline(Num
2 is greater) EndIf End Sub
54
Module Module1 Sub Main() ShowMessage(Greetin
gs) Console.WriteLine(Press
Enter) Console.ReadLine() End Sub Sub
ShowMessage(Text As String) Console.WriteLine(Te
xt) End Sub End Module
55
Module Module1 Sub Main() ShowMessage(Greetin
gs, 3) Console.WriteLine(Press
Enter) Console.ReadLine() End Sub Sub
ShowMessage(Text As String, Times as
Integer) Dim Index As Integer For 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 Forms 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
  • To compute the area of a circle using a Function
    procedure
  • area 3.14 radius radius
  • Problem specification
  • Input One real value radius
  • Output one result value the area of a circle
  • Process Formula provided area 3.14 radius
    radius

65
Intro to Function procedures
  • The problem to be solved
  • To compute the area of a circle using a Function
    procedure
  • area 3.14 radius radius
  • How to solve the problem? There exist many (at
    least 2) different approaches
  • Writing all the code in sub Main() bad solution
  • Using a Function procedure as a separate
    independent program unit the best solution

66
All the code in Sub Main()
Module Module1 Sub Main() Dim
radius, area As Single Const PI As Single
3.14 Console.WriteLine("Enter real
number as radius") radius
Console.ReadLine() area PI radius
radius Console.WriteLine("Result
is 0", area) End Sub End Module
67
Using a Function procedure
  1. Data exchange btw procedures
  2. Result value generated within the Called/Slave
    procedure.
  3. Result value generated within the Called/Slave
    procedure to be transferred to Calling/Caller/Mast
    er procedure using one of the following two ways
  4. Through return statement
  5. Through the procedure name
  6. One only value may be transferred following the
    steps above.
  7. Result including gt1 values may be transferred to
    Caller/Master procedure through the ByRef type of
    formal parameters.

68
Using a Function procedure
Module Module1 Sub Main()
Console.WriteLine(Area(10)) Dim x As
Single 20 Console.WriteLine(Area(x))
Console.WriteLine(Area(x 2 5)) End
Sub Function Area(rad As Single) As
Single Const PI As Single 3.14 Dim result As
Single result Pi rad rad return result
End Function End Module
69
Using a Function procedure
Module Module1 Sub Main()
Console.WriteLine(Area(10)) Dim x As
Single 20 Console.WriteLine(Area(x))
Console.WriteLine(Area(x 2 5)) End
Sub Function Area(rad As Single) As
Single Const PI As Single 3.14 return Pi
rad rad End Function End Module
70
Using a Function procedure
Module Module1 Sub Main()
Console.WriteLine(Area(10)) Dim x As
Single 20 Console.WriteLine(Area(x))
Console.WriteLine(Area(x 2 5)) End
Sub Function Area(rad As Single) As
Single Const PI As Single 3.14 Dim result As
Single result Pi rad rad Area result
End Function End Module
71
Using a Function procedure
Module Module1 Sub Main()
Console.WriteLine(Area(10)) Dim x As
Single 20 Console.WriteLine(Area(x))
Console.WriteLine(Area(x 2 5)) End
Sub Function Area(rad As Single) As
Single Const PI As Single 3.14 Area Pi
rad rad End Function End Module
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

Note the assignment
Return type
Returns a value
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

Note the assignment
Return type
Returns a value
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

Note the call
Return type
Returns a value
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

Note the call
Return type
Returns a value
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 gt1 values to the calling procedure
    1/1Calling statements
  • variable funcname(arg1, arg2, etc)
  • subname(arg1, arg2, etc)
  • Function structure
  • Function funcname(ByRef param1 As type, ByRef
    param2 As type, etc) As type statements param1
    ltexpressiongt param2 ltexpressiongt
  • Return returnvalue
  • End Function
  • Sub structure
  • Sub subname(ByRef param1 As type, ByRef param2
    As type, etc) statements param1 ltexpressiongt
    param2 ltexpressiongt
  • 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 20 Dim
Item2 As Integer 4 Dim Sum As Integer Sum
Add(Item1, Item2) Console.WriteLine("012"
, 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
20 Dim Item2 As Integer 4 Dim 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
/ p2 Return p1 p2 End Function
84
Example of calling a user defined Sub By
reference Sub Main() Dim Item1 As Integer
20 Dim Item2 As Integer 4 Dim 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)    declarati
    ons 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
ReminderNext class Quiz 3 (20 min)on Loops
and Procedures /Sub-s and Function-s/
96
Questions?
97
  • Thank You
  • For
  • Your Attention!
About PowerShow.com