Chapter 6 - Procedures Outline

advertisement
1
Chapter 6 - Procedures
Outline
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
6.9
6.10
6.11
6.12
6.13
6.14
6.15
6.16
Introduction
Modules, Classes and Procedures
Sub Procedures
Function Procedures
Methods
Argument Promotion
Option Strict and Data Type Conversions
Value Types and Reference Types
Passing Arguments: Pass-by-Value vs. Pass-by-Reference
Duration of Identifiers
Scope Rules
Random-Number Generation
Example: Game of Chance
Recursion
Example Using Recursion: The Fibonacci Series
Recursion vs. Iteration
 2002 Prentice Hall. All rights reserved.
2
Outline
6.17
6.18
Procedure Overloading and Optional Arguments
6.17.1 Procedure Overloading
6.17.2 Optional Arguments
Modules
 2002 Prentice Hall. All rights reserved.
3
6.2 Modules, Classes and Procedures
• Framework Class Library
– Provides a rich collection of “prepackaged” classes and
methods for performing many operations
•
•
•
•
•
Mathematical calculations
String manipulations
Character manipulations
Input/output operations
Error checking
 2002 Prentice Hall. All rights reserved.
4
6.2 Modules, Classes and Procedures
• Programmer-defined procedures
– FCL cannot provide every conceivable feature that a
programmer could want
– Three types of procedures
• Sub procedures
• Function procedures
• Event procedures
– A procedure is invoked by a procedure call
 2002 Prentice Hall. All rights reserved.
5
6.2 Modules, Classes and Procedures
• Division of code into procedures
– Several motivations to divide code into procedures
• Divide-and-conquer approach makes program development
more manageable
• Software reusability
• Avoids the repetition of code in a program
 2002 Prentice Hall. All rights reserved.
6
6.2 Modules, Classes and Procedures
• Earlier programs had only one procedure that
called FCL methods
• Next program contains two customized procedures
 2002 Prentice Hall. All rights reserved.
7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
The
The
The
The
Outline
' Fig. 6.2: Payment.vb
' Sub procedure that prints payment information.
Module modPayment
Payment.vb
Sub Main()
' call Sub procedure PrintPay 4 times
PrintPay(40, 10.5)
PrintPay receives the values of each argument and
PrintPay(38, 21.75)
them in the parameters variables hours and wage
PrintPay(20, 13)storesPrintPay
executes when it
PrintPay(50, 14)
is invoked by Main
Console.ReadLine() ' prevent window from closing
End Sub ' Main
' print amount of money earned in command window
Sub PrintPay(ByVal hours As Double, ByVal wage As Decimal)
' pay = hours * wage
Console.WriteLine("The payment is {0:C}", hours * wage)
End Sub ' PrintPay
End Module ' modPayment
payment
payment
payment
payment
is
is
is
is
$420.00
$826.50
$260.00
$700.00
Notice that PrintPay appears within modPayment.
All procedures must be defined inside a module or a class
Program Output
 2002 Prentice Hall.
All rights reserved.
8
6.3 Sub Procedures
• Format of a procedure definition
Sub procedure-name(parameter-list)
declarations and statements
End Sub
• Procedure header
– The first line is known as the procedure header
• Procedure-name
– Directly follows the Sub keyword
– Can be any valid identifier
– It is used to call this Sub procedure within the program
• Procedure body
– The declarations and statements in the procedure definition
form the procedure body
 2002 Prentice Hall. All rights reserved.
9
6.4 Function Procedures
• Similar to Sub procedures
• One important difference
– Function procedures return a value to the caller
 2002 Prentice Hall. All rights reserved.
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Outline
' Fig. 6.3: SquareInteger.vb
' Function procedure to square a number.
Module modSquareInteger
SquareInteger.vb
Sub Main()
Dim i As Integer ' counter
The For structure displays the results
Square isofinvoked
Console.WriteLine("Number"
& vbTab &
"Square"
squaringwith
the the
Integers
from
1-10 & vbCrLf)
expression Square(i)
' square numbers from 1 to 10
For i = 1 To 10
Console.WriteLine(i & vbTab & Square(i))
Next
End Sub ' Main
' Function Square is executed
' only when the function is explicitly called.
Function Square(ByVal y As Integer) As Integer
Return y ^ 2
The Return statement
End Function ' Square
terminates execution of
the procedure and returns the result of y ^ 2
End Module ' modSquareInteger
 2002 Prentice Hall.
All rights reserved.
11
Number
Square
1
2
3
4
5
6
7
8
9
10
1
4
9
16
25
36
49
64
81
100
Outline
SquareInteger.vb
Program Output
 2002 Prentice Hall.
All rights reserved.
12
6.4 Function Procedures
• Format of a Function procedure definition
Function procedure-name(parameter-list) As return-type
declarations and statements
End Function
• Return-type
– Indicates the data type of the result returned from the
Function to its caller
• Return expression
– Can occur anywhere in a Function
– It returns exactly one value
– Control returns immediately to the point at which that
procedure was invoked
 2002 Prentice Hall. All rights reserved.
13
6.5 Methods
• Definition of method
– A method is any procedure that is contained within a class
• FCL methods
• Custom methods in programmer-defined classes
 2002 Prentice Hall. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'
'
14
Remember that all forms inherit from class
Fig. 6.4: Maximum.vb
System.Windows.Forms.Form
Program finds the maximum
of three numbers input.
Public Class FrmMaximum
Inherits System.Windows.Forms.Form
Outline
Maximum.vb
' prompts for three inputs
Friend WithEvents lblOne As System.Windows.Forms.Label
Friend WithEvents lblTwo As System.Windows.Forms.Label
Friend WithEvents lblThree As System.Windows.Forms.Label
' displays result
Friend WithEvents lblMaximum As System.Windows.Forms.Label
' read
Friend
Friend
Friend
three numbers
WithEvents txtFirst As System.Windows.Forms.TextBox
WithEvents txtSecond As System.Windows.Forms.TextBox
WithEvents txtThird As System.Windows.Forms.TextBox
Event handler cmdMaximum_Click Handles the
reads in
inputs
calculate
results is clicked
event
whichand
Button
cmdMaximum
'
Friend WithEvents cmdMaximum As System.Windows.Forms.Button
' Visual Studio .NET generated
code
These are declarations
of all the controls used in the GUI.
Create these components visually, using the Toolbox
' obtain values in each text box, call procedure Maximum
Private Sub cmdMaximum_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdMaximum.Click
 2002 Prentice Hall.
All rights reserved.
15
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Outline
Dim value1, value2, value3 As Double
value1 = txtFirst.Text
value2 = txtSecond.Text
value3 = txtThird.Text
The values in the three TextBoxes are
Maximum.vb
retrieved using the Text property
lblMaximum.Text = Maximum(value1, value2, value3)
End Sub ' cmdMaximum_Click
' find maximum of three parameter
values
Call to methods
that are defined in a class in the FCL
Function Maximum(ByVal valueOne
Double,
_ nameinand
Call
toAsmethods
defined
thethe
class
must
include
the class
dotthat
(.)contains
operator
ByVal valueTwo As Double, ByVal valueThree As Double)
the method call need only specify the method name
Return Math.Max(Math.Max(valueOne, valueTwo), valueThree)
End Function ' Maximum
End Class ' FrmMaximum
Program Output
 2002 Prentice Hall.
All rights reserved.
16
6.5 Methods
Parameter Info window
Fig. 6.5
Parameter Info feature of the Visual Studio .NET IDE.
 2002 Prentice Hall. All rights reserved.
17
6.5 Methods
Fig. 6.6
IntelliSense feature of the Visual Studio .NET IDE.
 2002 Prentice Hall. All rights reserved.
18
6.5 Methods
Method
Desc rip tion
Exa m p le
Abs(x)
returns the absolute value of x
Ceiling(x)
rounds x to the smallest integer
not less than x
Cos(x)
returns the trigonometric cosine
of x (x in radians)
Abs(23.7) is 23.7
Abs(0) is 0
Abs(-23.7) is 23.7
Ceiling(9.2) is 10.0
Ceiling(-9.8) is -9.0
Cos(0.0) is 1.0
Exp(x)
returns the exponential ex
Floor(x)
rounds x to the largest integer
not greater than x
Log(x)
returns the natural logarithm of x
(base e)
Max(x, y)
returns the larger value of x and
y (also has versions for
Single, Integer and
Exp(1.0) is approximately
2.71828182845905
Exp(2.0) is approximately
7.38905609893065
Floor(9.2) is 9.0
Floor(-9.8) is -10.0
Log(2.718281828459045
1)
is approximately 1.0
Log(7.389056098930650
4)
is approximately 2.0
Max(2.3, 12.7) is 12.7
Max(-2.3, -12.7) is -2.3
Long values)
Min(x, y)
Pow(x, y)
returns the smaller value of x
and y (also has versions for
Single, Integer and
Long values)
calculates x raised to power y
y
(x )
Fig. 6.7
 2002 Prentice Hall. All rights reserved.
Min(2.3, 12.7) is 2.3
Min(-2.3, -12.7) is -12.7
Pow(2.0, 7.0) is 128.0
Pow(9.0, .5) is 3.0
Math class methods.
19
6.5 Methods
Sin(x)
returns the trigonometric sine of
x (x in radians)
Sin(0.0) is 0.0
Sqrt(x)
returns the square root of x
Tan(x)
returns the trigonometric
tangent of x (x in radians)
Sqrt(9.0) is 3.0
Sqrt(2.0) is
1.4142135623731
Tan(0.0) is 0.0
Fig. 6.7 Math c la ss m e thod s.
Fig. 6.7
 2002 Prentice Hall. All rights reserved.
Math class methods.
20
6.6 Argument Promotion
• Coercion of arguments
– The forcing of arguments to be appropriate data type so that
they can be passed to a procedure
• Widening conversion
– Occurs when a type is converted to another type without
losing data
• Narrowing conversion
– Occurs when there is potential for data loss during the
conversion
 2002 Prentice Hall. All rights reserved.
21
6.6 Argument Promotion
Typ e
Conversion Typ es
Boolean
Object
Byte
Decimal, Short, Integer, Long, Decimal, Single, Double or
Object
Decimal, Double, Single, Integer, Long, Object or Short
Object
Single, Double, or Object
Object
Double, Decimal, Single, Long or Object
Decimal, Double, Single, or Object
Char
Date
Decimal
Double
Integer
Long
Object
Short
Single
String
Fig. 6.8
none
Decimal, Double, Single, Integer, Long or Object
Double or Object
Object
Wid ening c onversions.
Fig. 6.8
 2002 Prentice Hall. All rights reserved.
Widening conversions.
22
6.7 Option Strict and Data-Type Conversions
• Option Explicit
– Set to On by default
– Forces the programmer to declare explicitly all variables
before they are used
• Option strict
– Set to Off by default
– When set to On, it forces the programmer to perform an
explicit conversion for all narrowing conversions
• Class Convert
– The methods in class Convert change data types explicitly
 2002 Prentice Hall. All rights reserved.
23
6.7 Option Strict and Data-Type Conversions
Fig. 6.9
 2002 Prentice Hall. All rights reserved.
Property Pages dialog with Option Strict set to On.
24
6.8 Value Types and Reference Types
• Variable of a value type
– Contains the actual data
– Used for a single piece of data
• Integer
• Double
• Variable of a reference type
– Contains a location in memory where
– Known as objects
• Literals
– Values typed directly in program code
– Corresponds to one of the primitive data types
 2002 Prentice Hall. All rights reserved.
25
6.8 Value Types and Reference Types
Type
Size in
bits
Values
Boolean
16
True or False
Char
Byte
Date
16
8
64
One Unicode character
Decimal
Short
Integer
128
16
32
1.0E-28 to 7.9E+28
–32,768 to 32,767
–2,147,483,648 to
2,147,483,647
Long
64
–9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
1.5E-45 to 3.4E+38
5.0E–324 to 1.7E+308
Standard
(Unicode character set)
0 to 255
1 January 0001 to 31 December 9999
0:00:00 to 23:59:59
Single
32
Double
64
Data of any type
Object
32
0 to ~2000000000 Unicode characters
String
Fig. 6.10 Visual Basic primitive data types.
(IEEE 754 floating point)
(IEEE 754 floating point)
(Unicode character set)
Fig. 6.10 Visual Basic primitive data types.
 2002 Prentice Hall. All rights reserved.
26
6.8 Value Types and Reference Types
Typ e
Typ e c ha ra c ter
Exa mp le
Char
c
"u"c
Single
Double
Decimal
Short
Integer
Long
F
R
D
S
I
L
9.802E+31F
6.04E-187R
128309.76D
3420S
-867I
19235827493259374L
Fig. 6.11
Litera ls w ith typ e c ha ra c te rs.
Fig. 6.11 Literals with type characters.
 2002 Prentice Hall. All rights reserved.
27
6.9 Passing Arguments: Pass-by-Value vs.
Pass-by-Reference
• Pass-by-value
– The program makes a copy of the argument’s value and
passes that copy to the called procedure
• Pass-by-reference
– The caller gives the called procedure the ability to access
and modify the caller’s original data directly.
 2002 Prentice Hall. All rights reserved.
28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
' Fig. 6.12: ByRefTest.vb
' Demonstrates passing by reference.
Module modByRefTest
Outline
ByRefTest.vb
' squares three values ByVal and ByRef, displays results
Sub Main()
When number1 is passed, a copy of
Dim number1 As Integer = 2
the value is passed to the procedure
Console.WriteLine("Passing a value-type argument by value:")
Console.WriteLine("Before calling SquareByValue, " & _
"number1 is {0}", number1)
SquareByValue(number1) ' passes number1 by value
Console.WriteLine("After returning from SquareByValue, " & _
"number1 is {0}" & vbCrLf, number1)
Dim number2 As
A reference to the value stored
Integer
= 2
in number2
is being passed
Console.WriteLine("Passing a value-type argument" & _
" by reference:")
Console.WriteLine("Before calling SquareByReference, " & _
"number2 is {0}", number2)
SquareByReference(number2) ' passes number2 by reference
Console.WriteLine("After returning from " & _
"SquareByReference, number2 is {0}" & vbCrLf, number2)
Dim number3 As Integer = 2
 2002 Prentice Hall.
All rights reserved.
29
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Console.WriteLine("Passing a value-type argument" & _
" by reference, but in parentheses:")
Console.WriteLine("Before calling SquareByReference " & _
"using parentheses, number3 is {0}", number3)
SquareByReference((number3)) ' passes number3 by value
ByVal indicates that
value-type
Console.WriteLine("After
returning
from " & _
"SquareByReference,
number3
is
{0}",
number3)
arguments should be passed by value
Outline
ByRefTest.vb
End Sub ' Main
Enclosing
arguments in parenthesis
' squares number by value (note ByVal keyword)
forces
pass-by-value
Sub SquareByValue(ByVal
number As Integer)
Console.WriteLine("After entering SquareByValue, " & _
"number is {0}", number)
ByRef gives direct access to the
number *= number
value stored inexiting
the original
variable
Console.WriteLine("Before
SquareByValue,
" & _
"number is {0}", number)
End Sub ' SquareByValue
' squares number by reference (note ByRef keyword)
Sub SquareByReference(ByRef number As Integer)
Console.WriteLine("After entering SquareByReference" & _
", number is {0}", number)
number *= number
Console.WriteLine("Before exiting SquareByReference" & _
", number is {0}", number)
End Sub ' SquareByReference
End Module ' modByRefTest
 2002 Prentice Hall.
All rights reserved.
30
Passing a value-type argument by value:
Before calling SquareByValue, number1 is 2
After entering SquareByValue, number is 2
Before exiting SquareByValue, number is 4
After returning from SquareByValue, number1 is 2
Outline
Program Output
Passing a value-type argument by reference:
Before calling SquareByReference, number2 is 2
After entering SquareByReference, number is 2
Before exiting SquareByReference, number is 4
After returning from SquareByReference, number2 is 4
Passing a value-type argument by reference, but in parentheses:
Before calling SquareByReference using parentheses, number3 is 2
After entering SquareByReference, number is 2
Before exiting SquareByReference, number is 4
After returning from SquareByReference, number3 is 2
 2002 Prentice Hall.
All rights reserved.
31
6.10 Duration of Identifiers
• Identifier’s duration
– Period during which the identifier exists in memory
• Identifier’s scope
– Portion of a program in which the variable’s identifier can
be referenced
• Automatic duration
– Identifiers that represent local variables in a procedure have
automatic duration
• Instance variable
– A variable declared in a class
– They exist as long as their containing class is loaded in
memory
 2002 Prentice Hall. All rights reserved.
32
6.11 Scope Rules
• Possible scopes
– Class scope
• Begins at the class identifier after keyword Class and
terminates at the End Class statement
– Module scope
• Variable declared in a module have module scope, which is
similar to class scope
– Namespace scope
• Procedures defined in a module have namespace scope, which
generally means that they may be accessed throughout a
project
– Block scope
• Identifiers declared inside a block, such as the body of a
procedure definition or the body of an If/Then selection
structure, have block scope
 2002 Prentice Hall. All rights reserved.
33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
' Fig. 6.13: Scoping.vb
' Demonstrates scope rules and instance variables.
Public Class FrmScoping
Inherits System.Windows.Forms.Form
Outline
Scoping.vb
This variable is hidden in any procedure
Friend WithEvents lblOutput As System.Windows.Forms.Label
that declares a variable named value
' Windows Form Designer generated code
' instance variable can be used anywhere in class
Dim value As Integer = 1
None of the method calls modifies this variable
' demonstrates class scope and block scope
– Private
both methods
refer to variables in other
scopesAs
Sub FrmScoping_Load(ByVal
sender
System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
' variable local to FrmScoping_Load hides instance variable
Dim value As Integer = 5
lblOutput.Text = "local variable value in" & _
" FrmScoping_Load is " & value
MethodA()
MethodB()
MethodA()
MethodB()
'
'
'
'
MethodA has automatic local value
MethodB uses instance variable value
MethodA creates new automatic local value
instance variable value retains its value
lblOutput.Text
&= vbCrLf
& vbCrLf
Automatic
variable value
is destroyed
"value in CScoping_Load is " &
when
MethodA
terminates
End Sub ' FrmScoping_Load
& "local variable " & _
value
' automatic local variable value hides instance variable
Sub MethodA()
Dim value As Integer = 25 ' initialized after each call
 2002 Prentice Hall.
All rights reserved.
34
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _
"value in MethodA is " & value & " after entering MethodA"
value += 1
lblOutput.Text
&= vbCrLf
"local value,
variable " & _
When MethodB
procedure
refers to& variable
"value in MethodA is " & value & " before exiting MethodA"
the instance
variable value (line 12) is used.
End Sub ' MethodA
Outline
Scoping.vb
' uses instance variable value
Sub MethodB()
lblOutput.Text &= vbCrLf & vbCrLf & "instance variable" & _
" value is " & value & " after entering MethodB"
value *= 10
lblOutput.Text &= vbCrLf & "instance variable " & _
"value is " & value & " before exiting MethodB"
End Sub ' MethodB
End Class ' FrmScoping
 2002 Prentice Hall.
All rights reserved.
35
6.12 Random-Number Generation
• Random class
– Produces values at random
– Keyword New creates an object of a specified type and
returns the object’s location in memory
– Next Method
• Generates a positive Integer value between zero and the
constant Int32.MaxValue (2,147,483,647)
• When a single argument is passed to Next, the values returned
will be in the range from 0 to the value of that argument
– Scaling
• By passing two arguments, the programmer is allowed to
specify the bottom range too
 2002 Prentice Hall. All rights reserved.
36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Outline
' Fig. 6.14: RandomInteger.vb
' Generating random integers.
Imports System.Windows.Forms
RandomInteger.vb
Module modRandomInteger
Sub Main()
Dim randomObject As Random = New Random()
Note that we must use 7 as the second argument
Dim randomNumber As Integer
Dim output As String = ""to produce integers in the range from 1-6
Dim i As Integer
For i = 1 To 20
randomNumber = randomObject.Next(1, 7)
output &= randomNumber & " "
If i Mod 5 = 0 Then ' is i a multiple of 5?
output &= vbCrLf
End If
Next
Go to the next line every time
five numbers are generated
MessageBox.Show(output, "20 Random Numbers from 1 to 6", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub ' Main
End Module ' modRandomInteger
 2002 Prentice Hall.
All rights reserved.
37
6.14 Recursion
• Recursive procedure
– It is a procedure that calls itself either directly or indirectly
– It is called to solve a problem
– The procedure knows how to solve only the simples case
(base case)
– For complex problems, the procedure divides the problem
into a piece that it can perform and a piece that it does not
know how to perform
– Recursive call
• The procedure invokes a fresh copy of itself to work on the
smaller problem
 2002 Prentice Hall. All rights reserved.
38
6.14 Recursion
5!
5!
5 * 4!
5 * 4!
4 * 3!
Final value = 120
5! = 5 * 24 = 120 is returned
4 * 3!
3 * 2!
4! = 4 * 6 = 24 is returned
3 * 2!
2 * 1!
1
(a) Procession of recursive calls
3! = 3 * 2 = 6 is returned
2 * 1!
1
1 returned
(b) Values returned from each recursive call
Fig. 6.18 Recursive evaluation of 5!.
 2002 Prentice Hall. All rights reserved.
2! = 2 * 1 = 2 is returned
39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
' Fig. 6.19: Factorial.vb
' Calculating factorials using recursion.
Public Class FrmFactorial
Inherits System.Windows.Forms.Form
Outline
Factorial.vb
Friend WithEvents lblEnter As Label
' prompts for Integer
Friend WithEvents lblFactorial As Label ' indicates output
Friend WithEvents txtInput As TextBox
' reads an Integer
Friend WithEvents txtDisplay As TextBox ' displays output
Friend WithEvents cmdCalculate As Button ' generates output
Conversion from String to Integer
' Visual Studio .NET generated code
Private Sub cmdCalculate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdCalculate.Click
Dim value As Integer = Convert.ToInt32(txtInput.Text)
Dim i As Integer
Dim output As String
txtDisplay.Text = ""
For i = 0 To value
txtDisplay.Text &= i & "! = " & Factorial(i) & vbCrLf
Next
End Sub ' cmdCalculate_Click
 2002 Prentice Hall.
All rights reserved.
40
31
32
33
34
35
36
37
38
39
40
41
42
43
' recursively generates factorial of number
number
is greater
than 1, a recursive
callLong)
to As Long
Function
Factorial(ByVal
number As
If
Factorial is made with a slightly simpler problem
If number <= 1 Then ' base case
Return 1
Else
Return number * Factorial(number - 1)
End If
Outline
Factorial.vb
End Function ' Factorial
End Class '
Forgetting to return a value from a recursive
procedure can result in logic errors
FrmFactorial
 2002 Prentice Hall.
All rights reserved.
41
6.16 Recursion vs. Iteration
• Iteration
– Involves an explicit repetition structure
– Uses a repetition structure
• For, While or Do/Loop Until
• Recursion
– Achieves repetition through repeated procedure calls
– Uses a selection structure
• If/Then, If/Then/Else or Select
– Recursive calls take time and consume additional memory
 2002 Prentice Hall. All rights reserved.
42
6.17 Procedure Overloading and Optional
Arguments
• Overloading
– Allows multiple procedures with the same name, but
differing numbers and types of arguments
– The overloading of procedures that perform closely related
tasks can make programs more readable and understandable
• Optional arguments
– Defining an argument as optional allows the calling
procedure to decide what arguments to pass
 2002 Prentice Hall. All rights reserved.
43
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Outline
' Fig. 6.22: Overload.vb
' Using overloaded methods.
Public Class FrmOverload
Inherits System.Windows.Forms.Form
Overload.vb
Friend WithEvents outputLabel As Label
' Visual Studio .NET generated code
Private Sub FrmOverload_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
outputLabel.Text
= use
"Thethe
square
The compiler might
logicalof Integer 7 is " & _
square(7) & vbCrLf & "The square of Double " & _
name
“Square
of Integer”
"7.5
is " & square(7.5)
End Sub ' FrmOverload_Load
“Square of Double” for the Square
Function Square(ByVal value As Integer)
method
that specifies
a Double parameter
Return
Convert.ToInt32(value
^ 2)
As Integer
End Function ' Square
The compiler uses a logical name to
differ between the two Square methods
Function Square(ByVal value As Double) As Double
Return value ^ 2
End Function ' Square
End Class ' FrmOverload
 2002 Prentice Hall.
All rights reserved.
44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
' Fig. 6.23: Overload2.vb
' Using overloaded procedures with identical signatures and
' different return types.
Outline
Overload2.vb
Public Class FrmOverload2
Inherits System.Windows.Forms.Form
Friend WithEvents outputLabel As Label
' Visual Studio .NET generated code
Private Sub FrmOverload2_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
outputLabel.Text = "The square of Integer 7 is " & _
square(7) & vbCrLf & "The square of Double " & _
"7.5 is " & square(7.5)
End Sub ' FrmOverload2_Load
Function Square(ByVal value As Double) As Integer
Return Convert.ToInt32(value ^ 2)
End Function ' Square
Function Square(ByVal value As Double) As Double
Return value ^ 2
End Function ' Square
Procedure calls cannot be
distinguished by return type
End Class ' FrmOverload2
 2002 Prentice Hall.
All rights reserved.
45
Outline
The creating of overloaded procedures with identical parameter
lists and different return types produces a syntax error
Overload2.vb
Program Output
 2002 Prentice Hall.
All rights reserved.
46
6.17.2 Optional Arguments
• Optional
– Optional arguments are specified in the procedure header
with keyword Optional
• Syntax errors
– Not specifying a default value for an Optional parameter
is a syntax error
– Declaring a non-Optional parameter to the right of an
Optional parameter is a syntax error
 2002 Prentice Hall. All rights reserved.
47
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
' Fig 6.24 Power.vb
' Calculates the power of a value, defaults to square.
Public Class FrmPower
Inherits System.Windows.Forms.Form
Outline
Power.vb
Friend WithEvents txtBase As TextBox ' reads base
Friend WithEvents txtPower As TextBox ' reads power
Friend WithEvents inputGroup As GroupBox
Friend WithEvents lblBase As Label
' prompts for base
Friend WithEvents lblPower As Label ' prompts for power
Friend WithEvents lblOutput As Label ' displays output
Friend WithEvents cmdCalculate As Button ' generates output
' Visual Studio .NET generated code
' reads input and displays result
Private Sub cmdCalculate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdCalculate.Click
Determines whether txtPower contains a value
Dim value As Integer
' call version of Power depending on power input
If Not txtPower.Text = "" Then
value = Power(Convert.ToInt32(txtBase.Text), _
Convert.ToInt32(txtPower.Text))
Else
value = Power(Convert.ToInt32(txtBase.Text))
End If
lblOutput.Text = Convert.ToString(value)
End Sub ' cmdCalculate_Click
 2002 Prentice Hall.
All rights reserved.
48
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
' use iteration to calculate power
Function Power(ByVal base As Integer, _
Optional ByVal exponent As Integer = 2) As Integer
Dim total As Integer = 1
Dim i As Integer
For i = 1 To exponent
total *= base
Next
Outline
Power.vb
When omitted, the Optional
argument defaults to the value 2
Return total
End Function ' Power
End Class ' FrmPower
 2002 Prentice Hall.
All rights reserved.
Download