Download presentation
Presentation is loading. Please wait.
Published byPrudence Underwood Modified over 9 years ago
1
1 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, O’Reilly, 2002 Any Visual Basic book available in AUBG library Course lecturer: Assoc. Prof. Svetla Boytcheva PhD
2
2 INF110 Visual Basic Programming AUBG Spring semester 2011 Lecture 10 Title: Visual Basic (Procedures1: Sub-s & Function-s)
3
3 Lecture Contents: §Introducing the procedures concept §Advantages of using procedures §Sub procedure §Function procedure §Data exchange btw procedures §Parameter passing mechanism l Actual arguments l Formal parameters
4
4 Procedures (Sub-s and Function-s) INF110 Visual Basic Programming
5
5 The problem to be solved: To compute a Pythagorean triple using two integers m and n (m>n) as input and applying following formulas to compute all the three sides of a right triangle: side1 = m 2 –n 2 side2 = 2*m*nhypotenuse = m 2 +n 2 Problem specification: Input:Two integers: m, n Output: Three values: side1, side2, hypotenuse Process: Formulas provided
6
6 The problem to be solved: To compute 3 Pythagorean triples using two integers m and n (m>n) as input and applying following formulas to compute all the three sides of a right triangle: side1 = m 2 –n 2 side2 = 2*m*nhypotenuse = m 2 +n 2 Problem specification: Input:Two integers: m, n Output: Three values: side1, side2, hypotenuse Process: Formulas provided Introduction to Sub Procedures
7
7 The problem to be solved: To compute 3 Pythagorean triples using two integers m and n (m>n) as input and applying following formulas to compute all the three sides of a right triangle: side1 = m 2 –n 2 side2 = 2*m*nhypotenuse = m 2 +n 2 How to solve the problem? There exist many (at least 3) 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 program unit – the best solutionUsing a procedure as a separate independent program unit – the best solution Introduction to Sub Procedures
8
8 Module Module1 Sub Main() Sub Main() Dim m, n As Integer Dim m, n As Integer Dim Side1, Side2, Hypotenuse As Integer Dim 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*n Side1 = m*m - n*n Side2 = 2*m*n Side2 = 2*m*n Hypotenuse = m*m + n*n Hypotenuse = 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 Sub End Sub End Module Duplicating code solution
9
9 Source code in red has to be duplicated 3 times in order to solve the problem Module Module1 Sub Main() Sub Main() Dim m, n As Integer Dim m, n As Integer Dim Side1, Side2, Hypotenuse As Integer Dim 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*n Side1 = m*m - n*n Side2 = 2*m*n Side2 = 2*m*n Hypotenuse = m*m + n*n Hypotenuse = 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 Sub End Sub End Module Duplicating code solution
10
10 Source code after being duplicated 3 times in order to solve the problem Module Module1 Sub Main() Sub Main() Dim m, n As Integer Dim m, n As Integer Dim Side1, Side2, Hypotenuse As Integer Dim 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*n Side1 = m*m - n*n Side2 = 2*m*n Side2 = 2*m*n Hypotenuse = m*m + n*n Hypotenuse = 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*n Side1 = m*m - n*n Side2 = 2*m*n Side2 = 2*m*n Hypotenuse = m*m + n*n Hypotenuse = 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*n Side1 = m*m - n*n Side2 = 2*m*n Side2 = 2*m*n Hypotenuse = m*m + n*n Hypotenuse = 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 Sub End Sub End Module Duplicating code solution
11
11 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 duplicatingcode 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 Using repetition control structure – better solution
12
12 Module Module1 Sub Main() Sub Main() Dim m, n, counter As Integer Dim m, n, counter As Integer Dim Side1, Side2, Hypotenuse As Integer Dim Side1, Side2, Hypotenuse As Integer For counter = 1 To 3 Step 1 For counter = 1 To 3 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 * n Side1 = m * m - n * n Side2 = 2 * m * n Side2 = 2 * m * n Hypotenuse = m * m + n * n Hypotenuse = 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 counter Next counter End Sub End Sub End Module Using repetition control structure – better solution
13
13 Module Module1 Sub Main() Sub Main() Dim m, n, counter As Integer Dim m, n, counter As Integer Dim Side1, Side2, Hypotenuse As Integer Dim Side1, Side2, Hypotenuse As Integer counter = 1 counter = 1 Do While counter <= 3 Do 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 * n Side1 = m * m - n * n Side2 = 2 * m * n Side2 = 2 * m * n Hypotenuse = m * m + n * n Hypotenuse = 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 + 1 counter = counter + 1 Loop Loop End Sub End Sub End Module Using repetition control structure – better solution
14
14 Module Module1 Sub Main() Sub Main() Dim m, n, counter As Integer Dim m, n, counter As Integer Dim Side1, Side2, Hypotenuse As Integer Dim Side1, Side2, Hypotenuse As Integer counter = 1 counter = 1 Do Do 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 * n Side1 = m * m - n * n Side2 = 2 * m * n Side2 = 2 * m * n Hypotenuse = m * m + n * n Hypotenuse = 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 + 1 counter = counter + 1 Loop Until counter = 3 Loop Until counter = 3 End Sub End Sub End Module Using repetition control structure – better solution
15
15 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() Sub Main()...... End Sub 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/encapsulated in a separate independent program unit - procedure. VB supports two types of separate program units – subroutines Sub and functions Function. Using a procedure – best solution
16
16 Applying this structured approach means a : The new procedure has to be defined/declared Applying this structured approach means a new skeleton/structure of the console application: The new procedure has to be defined/declared Module Module1 Sub Main() Sub Main()...... End Sub End Sub Sub PythagorTriple()... End Sub End Module Using a procedure – best solution
17
17 Applying this structured approach means a new skeleton/structure of the console application: The new procedure has to be defined/declared Module Module1 Sub Main() Sub Main()...... End Sub End Sub Sub PythagorTriple() Sub PythagorTriple() Dim m, n As Integer Dim m, n As Integer Dim Side1, Side2, Hypotenuse As Integer Dim 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 * n Side1 = m * m - n * n Side2 = 2 * m * n Side2 = 2 * m * n Hypotenuse = m * m + n * n Hypotenuse = 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 Sub End Sub End Module Using a procedure – best solution
18
18 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() Sub Main()......PythagorTriple() Call PythagorTriple() Call PythagorTriple()PythagorTriple()...... End Sub End Sub Sub PythagorTriple() Sub PythagorTriple()...... End Sub End Sub End Module Using a procedure – best solution
19
19 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() Sub Main()...... PythagorTriple():Call PythagorTriple() PythagorTriple() : PythagorTriple() :PythagorTriple() PythagorTriple() : PythagorTriple() : PythagorTriple()...... End Sub End Sub Sub PythagorTriple() Sub PythagorTriple()...... End Sub End Sub End Module Using a procedure – best solution
20
20 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() Sub Main()......PythagorTriple() End Sub End Sub Sub PythagorTriple() Sub PythagorTriple()...... End Sub End Sub End Module Using a procedure – best solution
21
21 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() Sub Main()...... Dim counter As Integer = 1 Do While counter <= 10 PythagorTriple() counter = counter + 1 Loop...... End Sub End Sub Sub PythagorTriple() Sub PythagorTriple()...... End Sub End Sub End Module Using a procedure – best solution
22
22 Module Module1 Sub Main() Sub Main() PythagorTriple() PythagorTriple() Call PythagorTriple() Call PythagorTriple() End Sub End Sub Sub PythagorTriple() Sub PythagorTriple() Dim m, n As Integer Dim m, n As Integer Dim Side1, Side2, Hypotenuse As Integer Dim 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 * n Side1 = m * m - n * n Side2 = 2 * m * n Side2 = 2 * m * n Hypotenuse = m * m + n * n Hypotenuse = 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 Sub End Sub End Module Using a procedure – best solution Entire program source text
23
23 Sub PythagorTriple() Dim m, n As Integer Dim m, n As Integer Dim Side1, Side2, Hypotenuse As Integer Dim 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 Sub 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(). Using a procedure – best solution All I-P-O encapsulated inside
24
24 Ways to assign data for m,n: 1.Initialization Dim m As Integer = 8, n As Integer = 6 2.Assignment Dim m,n As Integer = 6 m = 8:n = 6 3.Typing /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. Using a procedure – best solution Data exchange btw procedures Introduction to parameter passing mechanism
25
25 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 and appears in the calling statement as a separated by comma. 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 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. Using a procedure – best solution Data exchange btw procedures Introduction to parameter passing mechanism
26
26 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(Arg1+4*Arg2, Arg2-6 mod 3 *2) Using a procedure – best solution Data exchange btw procedures Introduction to parameter passing mechanism
27
27 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. The non-parameter procedure body Sub PythagorTriple() Dim m, n As Integer Dim m, n As Integer Dim Side1, Side2, Hypotenuse As Integer Dim 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 * n Side1 = m * m - n * n Side2 = 2 * m * n Side2 = 2 * m * n Hypotenuse = m * m + n * n Hypotenuse = 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 Sub End Sub Is to be replaced with Using a procedure – best solution Data exchange btw procedures Introduction to parameter passing mechanism
28
28 Sub PythagorTriple(m As Integer, n As Integer) Dim Side1, Side2, Hypotenuse As Integer Dim Side1, Side2, Hypotenuse As Integer Side1 = m * m - n * n Side1 = m * m - n * n Side2 = 2 * m * n Side2 = 2 * m * n Hypotenuse = m * m + n * n Hypotenuse = m * m + n * n Console.WriteLine("Result is {0} {1} {2}", Side1, Side2, Hypotenuse) End Sub End Sub Using a procedure – best solution Data exchange btw procedures Introduction to parameter passing mechanism
29
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
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 functionality e.g. calculating some quantity
31
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
32 Sub-procedures (or just Subs) and Functions (or more precisely Function procedures) may be invoked (or called) any number of times.
33
33 The two coming slides present what B.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
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
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
36 Sub Procedures Performs one or more related tasks General syntax Sub ProcedureName() block of code – VB statements End Sub
37
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
38 Naming Sub procedures The rules for naming Sub procedures are the same as the rules for naming variables.
39
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
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
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
42 Sub Gaga() Example... Gaga()... End Sub Call Sub Gaga Return from Sub Gaga - a return is made to the statement following the Call A sub procedure is called by naming it in a statement. Note the brackets Sub procedure code
43
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
44 Example Console.Writeline(variable) The system Sub procedure Console.Writeline() displays the value of a variable.
45
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
46 It is possible for one sub procedure to call another, and so on. Effectively, we have a number of nested Sub calls.
47
47 Sub Procedures Calling Other Sub Procedures Sub Gaga()... FirstPart() End Sub Sub FirstPart() SecondPart() End Sub Sub SecondPart()... End Sub
48
48 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_parameters correspondence Adding Parameters
49
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
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
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
52 = actual data
53
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 Then Console.Writeline(“Num1 is greater”) Else Console.Writeline(“Num2 is greater”) EndIf End Sub
54
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
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 Integer For Index = 1 To Times Console.WriteLine(Text) Next Index End Sub End Module
56
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
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
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
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
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
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
62 Debugging Programs with Sub procedures are easier to debug Each Sub procedure can be checked individually before being placed into the program
63
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
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 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
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 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 solutionWriting all the code in sub Main() – bad solution Using a Function procedure as a separate independent program unit – the best solutionUsing a Function procedure as a separate independent program unit – the best solution
66
66 Module Module1 Sub Main() Sub Main() Dim radius, area As Single Dim radius, area As Single Const PI As Single = 3.14 Const PI As Single = 3.14 Console.WriteLine("Enter real number as radius:") Console.WriteLine("Enter real number as radius:") radius = Console.ReadLine() radius = Console.ReadLine() area = PI * radius * radius area = PI * radius * radius Console.WriteLine("Result is {0}", area) Console.WriteLine("Result is {0}", area) End Sub End Sub End Module All the code in Sub Main()
67
67 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/Master procedure using one of the following two ways: 1.Through return statement 2.Through the procedure name 4.One only value may be transferred following the steps above. 5.Result including >1 values may be transferred to Caller/Master procedure through the ByRef type of formal parameters. Using a Function procedure
68
68 Module Module1 Sub Main() Sub Main() Console.WriteLine(Area(10)) Console.WriteLine(Area(10)) Dim x As Single = 20 Dim 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 Sub End Sub Function Area(rad As Single) As Single 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 Function End Module Using a Function procedure
69
69 Module Module1 Sub Main() Sub Main() Console.WriteLine(Area(10)) Console.WriteLine(Area(10)) Dim x As Single = 20 Dim 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 Sub End Sub Function Area(rad As Single) As Single Function Area(rad As Single) As Single Const PI As Single = 3.14 return Pi * rad * rad End Function End Function End Module Using a Function procedure
70
70 Module Module1 Sub Main() Sub Main() Console.WriteLine(Area(10)) Console.WriteLine(Area(10)) Dim x As Single = 20 Dim 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 Sub End Sub Function Area(rad As Single) As Single 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 Function End Module Using a Function procedure
71
71 Module Module1 Sub Main() Sub Main() Console.WriteLine(Area(10)) Console.WriteLine(Area(10)) Dim x As Single = 20 Dim 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 Sub End Sub Function Area(rad As Single) As Single Function Area(rad As Single) As Single Const PI As Single = 3.14 Area = Pi * rad * rad End Function End Function End Module Using a Function procedure
72
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
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
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
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
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
77 Functions and Subs Pass back >1 values to the calling procedure 1/1 Calling 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 = : param2 = Return returnvalue End Function Sub structure Sub subname(ByRef param1 As type, ByRef param2 As type, etc) statements param1 = : param2 = End Sub
78
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
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
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
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
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( "{0}+{1}={2}", Sum, Item1, Item2) End Sub Function Add(P1 As Integer, P2 As Integer)As Integer Return P1 + P2 End Function
83
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
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
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
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
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
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
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
90 Exercise Create a program to test Squares10() Sub
91
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
92 Exercise Create a program to test Sum() Sub with two integer parameters
93
93 Exercise Create a program to test FindGreaterNum() Sub with two integer parameters
94
94 Exercise Create a program to test Add() Function with two integer parameters and return data type integer
95
95 Reminder Next class: Quiz 3 (20 min) on Loops and Procedures /Sub-s and Function-s/
96
96 Questions?
97
97 Thank You For Your Attention!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.