Chapter 6 - Procedures

71
2002 Prentice Hall. All rights reserved. 1 Chapter 6 - Procedures Outline 6.1 Introduction 6.2 Modules, Classes and Procedures 6.3 Sub Procedures 6.4 Function Procedures 6.5 Methods 6.6 Argument Promotion 6.7 Option Strict and Data Type Conversions 6.8 Value Types and Reference Types 6.9 Passing Arguments: Pass-by-Value vs. Pass-by- Reference 6.10 Duration of Identifiers 6.11 Scope Rules 6.12 Random-Number Generation 6.13 Example: Game of Chance 6.14 Recursion 6.15 Example Using Recursion: The Fibonacci Series 6.16 Recursion vs. Iteration

description

Chapter 6 - Procedures. - PowerPoint PPT Presentation

Transcript of Chapter 6 - Procedures

Page 1: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

1

Chapter 6 - Procedures

Outline6.1 Introduction6.2   Modules, Classes and Procedures6.3   Sub Procedures6.4   Function Procedures6.5   Methods6.6   Argument Promotion6.7   Option Strict and Data Type Conversions6.8   Value Types and Reference Types6.9   Passing Arguments: Pass-by-Value vs. Pass-by-Reference6.10   Duration of Identifiers6.11   Scope Rules6.12   Random-Number Generation6.13   Example: Game of Chance6.14   Recursion6.15   Example Using Recursion: The Fibonacci Series6.16   Recursion vs. Iteration

Page 2: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

2

Outline6.17   Procedure Overloading and Optional Arguments

6.17.1 Procedure Overloading6.17.2 Optional Arguments

6.18   Modules

Page 3: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

3

6.1 Introduction

• Divide and Conquer– The best way to develop and maintain a large program is to

construct it from small, manageable pieces.

Page 4: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

4

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

Page 5: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

5

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

Page 6: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

6

6.2 Modules, Classes and Procedures

Fig. 6.1 Hierarchical boss procedure/worker procedure relationship.

Boss

Worker1 Worker2 Worker3

Worker4 Worker5

Page 7: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

7

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

Page 8: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

8

6.2 Modules, Classes and Procedures

• Earlier programs had only one procedure that called FCL methods

• Next program contains two customized procedures

Page 9: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline9

Payment.vb

Program Output

1 ' Fig. 6.2: Payment.vb2 ' Sub procedure that prints payment information.3 4 Module modPayment5 6 Sub Main()7 8 ' call Sub procedure PrintPay 4 times9 PrintPay(40, 10.5)10 PrintPay(38, 21.75)11 PrintPay(20, 13)12 PrintPay(50, 14)13 14 Console.ReadLine() ' prevent window from closing15 End Sub ' Main16 17 ' print amount of money earned in command window18 Sub PrintPay(ByVal hours As Double, ByVal wage As Decimal)19 20 ' pay = hours * wage21 Console.WriteLine("The payment is {0:C}", hours * wage)22 End Sub ' PrintPay23 24 End Module ' modPayment

The payment is $420.00The payment is $826.50The payment is $260.00The payment is $700.00

PrintPay executes when it is invoked by Main

PrintPay receives the values of each argument and stores them in the parameters variables hours and wage

Notice that PrintPay appears within modPayment. All procedures must be defined inside a module or a class

Page 10: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

10

6.3 Sub Procedures

• Format of a procedure definitionSub procedure-name(parameter-list) declarations and statementsEnd 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

Page 11: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

11

6.4 Function Procedures

• Similar to Sub procedures• One important difference

– Function procedures return a value to the caller

Page 12: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline12

SquareInteger.vb

1 ' Fig. 6.3: SquareInteger.vb2 ' Function procedure to square a number.3 4 Module modSquareInteger5 6 Sub Main()7 Dim i As Integer ' counter8 9 Console.WriteLine("Number" & vbTab & "Square" & vbCrLf)10 11 ' square numbers from 1 to 1012 For i = 1 To 1013 Console.WriteLine(i & vbTab & Square(i))14 Next15 16 End Sub ' Main17 18 ' Function Square is executed19 ' only when the function is explicitly called.20 Function Square(ByVal y As Integer) As Integer21 Return y ^ 222 End Function ' Square23 24 End Module ' modSquareInteger

The For structure displays the results of squaring the Integers from 1-10Square is invoked with the

expression Square(i)

The Return statement terminates execution of the procedure and returns the result of y ^ 2

Page 13: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline13

SquareInteger.vb

Program Output

Number Square 1 12 43 94 165 256 367 498 649 8110 100

Page 14: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

14

6.4 Function Procedures

• Format of a Function procedure definitionFunction 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

Page 15: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

15

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

Page 16: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline16

Maximum.vb

1 ' Fig. 6.4: Maximum.vb2 ' Program finds the maximum of three numbers input.3 4 Public Class FrmMaximum5 Inherits System.Windows.Forms.Form6 7 ' prompts for three inputs8 Friend WithEvents lblOne As System.Windows.Forms.Label9 Friend WithEvents lblTwo As System.Windows.Forms.Label10 Friend WithEvents lblThree As System.Windows.Forms.Label11 12 ' displays result13 Friend WithEvents lblMaximum As System.Windows.Forms.Label14 15 ' read three numbers16 Friend WithEvents txtFirst As System.Windows.Forms.TextBox17 Friend WithEvents txtSecond As System.Windows.Forms.TextBox18 Friend WithEvents txtThird As System.Windows.Forms.TextBox19 20 ' reads inputs and calculate results21 Friend WithEvents cmdMaximum As System.Windows.Forms.Button22 23 ' Visual Studio .NET generated code24 25 ' obtain values in each text box, call procedure Maximum26 Private Sub cmdMaximum_Click(ByVal sender As System.Object, _27 ByVal e As System.EventArgs) Handles cmdMaximum.Click28

These are declarations of all the controls used in the GUI. Create these components visually, using the Toolbox

Remember that all forms inherit from class System.Windows.Forms.Form

Event handler cmdMaximum_Click Handles the event in which Button cmdMaximum is clicked

Page 17: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline17

Maximum.vb

Program Output

29 Dim value1, value2, value3 As Double30 31 value1 = txtFirst.Text32 value2 = txtSecond.Text33 value3 = txtThird.Text34 35 lblMaximum.Text = Maximum(value1, value2, value3)36 End Sub ' cmdMaximum_Click37 38 ' find maximum of three parameter values39 Function Maximum(ByVal valueOne As Double, _40 ByVal valueTwo As Double, ByVal valueThree As Double)41 42 Return Math.Max(Math.Max(valueOne, valueTwo), valueThree)43 End Function ' Maximum44 45 End Class ' FrmMaximum

The values in the three TextBoxes are retrieved using the Text property

Call to methods defined in the class that contains the method call need only specify the method name

Call to methods that are defined in a class in the FCL must include the class name and the dot (.) operator

Page 18: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

18

6.5 Methods

Fig. 6.5 Parameter Info feature of the Visual Studio .NET IDE.

Parameter Info window

Page 19: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

19

6.5 Methods

Fig. 6.6 IntelliSense feature of the Visual Studio .NET IDE.

Page 20: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

20

6.5 Methods

Fig. 6.7 Math class methods.

Method Description Example

Abs(x) returns the absolute value of x Abs(23.7) is 23.7 Abs(0) is 0 Abs(-23.7) is 23.7

Ceiling(x) rounds x to the smallest integer not less than x

Ceiling(9.2) is 10.0 Ceiling(-9.8) is -9.0

Cos(x) returns the trigonometric cosine of x (x in radians)

Cos(0.0) is 1.0

Exp(x) returns the exponential ex Exp(1.0) is approximately

2.71828182845905 Exp(2.0) is approximately

7.38905609893065 Floor(x) rounds x to the largest integer

not greater than x Floor(9.2) is 9.0 Floor(-9.8) is -10.0

Log(x) returns the natural logarithm of x

(base e) Log(2.7182818284590451) is approximately 1.0 Log(7.3890560989306504)

is approximately 2.0 Max(x, y) returns the larger value of x and

y (also has versions for

Single, Integer and

Long values)

Max(2.3, 12.7) is 12.7 Max(-2.3, -12.7) is -2.3

Min(x, y) returns the smaller value of x and y (also has versions for

Single, Integer and

Long values)

Min(2.3, 12.7) is 2.3 Min(-2.3, -12.7) is -12.7

Pow(x, y) calculates x raised to power y

(xy)

Pow(2.0, 7.0) is 128.0 Pow(9.0, .5) is 3.0

Page 21: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

21

6.5 Methods

Fig. 6.7 Math class 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 Sqrt(9.0) is 3.0 Sqrt(2.0) is

1.4142135623731 Tan(x) returns the trigonometric

tangent of x (x in radians) Tan(0.0) is 0.0

Fig. 6.7 Math class methods.

Page 22: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

22

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

Page 23: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

23

6.6 Argument Promotion

Type Conversion Types

Boolean Object

Byte Decimal, Short, Integer, Long, Decimal, Single, Double or

Object Char Decimal, Double, Single, Integer, Long, Object or Short Date Object Decimal Single, Double, or Object Double Object Integer Double, Decimal, Single, Long or Object Long Decimal, Double, Single, or Object Object none

Short Decimal, Double, Single, Integer, Long or Object Single Double or Object String Object Fig. 6.8 Widening conversions.

Fig. 6.8 Widening conversions.

Page 24: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

24

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

Page 25: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

25

6.7 Option Strict and Data-Type Conversions

Fig. 6.9 Property Pages dialog with Option Strict set to On.

Page 26: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

26

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

Page 27: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

27

6.8 Value Types and Reference Types

Fig. 6.10 Visual Basic primitive data types.

Type Size in bits

Values Standard

Boolean 16 True or False

Char 16 One Unicode character (Unicode character set)

Byte 8 0 to 255 Date 64 1 January 0001 to 31 December 9999

0:00:00 to 23:59:59

Decimal 128 1.0E-28 to 7.9E+28 Short 16 –32,768 to 32,767 Integer 32 –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

Single 32 1.5E-45 to 3.4E+38 (IEEE 754 floating point)

Double 64 5.0E–324 to 1.7E+308 (IEEE 754 floating point)

Object 32 Data of any type

String 0 to ~2000000000 Unicode characters (Unicode character set)

Fig. 6.10 Visual Basic primitive data types.

Page 28: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

28

6.8 Value Types and Reference Types

Type Type character Example

Char c "u"c

Single F 9.802E+31F Double R 6.04E-187R Decimal D 128309.76D Short S 3420S Integer I -867I Long L 19235827493259374L Fig. 6.11 Literals with type characters.

Fig. 6.11 Literals with type characters.

Page 29: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

29

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.

Page 30: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline30

ByRefTest.vb

1 ' Fig. 6.12: ByRefTest.vb2 ' Demonstrates passing by reference.3 4 Module modByRefTest5 6 ' squares three values ByVal and ByRef, displays results7 Sub Main()8 Dim number1 As Integer = 29 10 Console.WriteLine("Passing a value-type argument by value:")11 Console.WriteLine("Before calling SquareByValue, " & _12 "number1 is {0}", number1)13 SquareByValue(number1) ' passes number1 by value14 Console.WriteLine("After returning from SquareByValue, " & _15 "number1 is {0}" & vbCrLf, number1)16 17 Dim number2 As Integer = 218 19 Console.WriteLine("Passing a value-type argument" & _20 " by reference:")21 Console.WriteLine("Before calling SquareByReference, " & _22 "number2 is {0}", number2)23 SquareByReference(number2) ' passes number2 by reference24 Console.WriteLine("After returning from " & _25 "SquareByReference, number2 is {0}" & vbCrLf, number2)26 27 Dim number3 As Integer = 228

When number1 is passed, a copy of the value is passed to the procedure

A reference to the value stored in number2 is being passed

Page 31: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline31

ByRefTest.vb

29 Console.WriteLine("Passing a value-type argument" & _30 " by reference, but in parentheses:")31 Console.WriteLine("Before calling SquareByReference " & _32 "using parentheses, number3 is {0}", number3)33 SquareByReference((number3)) ' passes number3 by value34 Console.WriteLine("After returning from " & _35 "SquareByReference, number3 is {0}", number3)36 37 End Sub ' Main38 39 ' squares number by value (note ByVal keyword)40 Sub SquareByValue(ByVal number As Integer)41 Console.WriteLine("After entering SquareByValue, " & _42 "number is {0}", number)43 number *= number44 Console.WriteLine("Before exiting SquareByValue, " & _45 "number is {0}", number)46 End Sub ' SquareByValue47 48 ' squares number by reference (note ByRef keyword)49 Sub SquareByReference(ByRef number As Integer)50 Console.WriteLine("After entering SquareByReference" & _51 ", number is {0}", number)52 number *= number53 Console.WriteLine("Before exiting SquareByReference" & _54 ", number is {0}", number)55 End Sub ' SquareByReference56 57 End Module ' modByRefTest

ByVal indicates that value-type arguments should be passed by value

ByRef gives direct access to the value stored in the original variable

Enclosing arguments in parenthesis forces pass-by-value

Page 32: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline32

Program Output

Passing a value-type argument by value:Before calling SquareByValue, number1 is 2After entering SquareByValue, number is 2Before exiting SquareByValue, number is 4After returning from SquareByValue, number1 is 2 Passing a value-type argument by reference:Before calling SquareByReference, number2 is 2After entering SquareByReference, number is 2Before exiting SquareByReference, number is 4After returning from SquareByReference, number2 is 4 Passing a value-type argument by reference, but in parentheses:Before calling SquareByReference using parentheses, number3 is 2After entering SquareByReference, number is 2Before exiting SquareByReference, number is 4After returning from SquareByReference, number3 is 2

Page 33: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

33

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

Page 34: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

34

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

Page 35: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline35

Scoping.vb

1 ' Fig. 6.13: Scoping.vb2 ' Demonstrates scope rules and instance variables.3 4 Public Class FrmScoping5 Inherits System.Windows.Forms.Form6 7 Friend WithEvents lblOutput As System.Windows.Forms.Label8 9 ' Windows Form Designer generated code10 11 ' instance variable can be used anywhere in class12 Dim value As Integer = 113 14 ' demonstrates class scope and block scope15 Private Sub FrmScoping_Load(ByVal sender As System.Object, _16 ByVal e As System.EventArgs) Handles MyBase.Load17 18 ' variable local to FrmScoping_Load hides instance variable19 Dim value As Integer = 520 21 lblOutput.Text = "local variable value in" & _22 " FrmScoping_Load is " & value23 24 MethodA() ' MethodA has automatic local value25 MethodB() ' MethodB uses instance variable value26 MethodA() ' MethodA creates new automatic local value27 MethodB() ' instance variable value retains its value28 29 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _30 "value in CScoping_Load is " & value31 End Sub ' FrmScoping_Load32 33 ' automatic local variable value hides instance variable34 Sub MethodA()35 Dim value As Integer = 25 ' initialized after each call

This variable is hidden in any procedure that declares a variable named value

Automatic variable value is destroyed when MethodA terminates

None of the method calls modifies this variable – both methods refer to variables in other scopes

Page 36: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline36

Scoping.vb

36 37 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _38 "value in MethodA is " & value & " after entering MethodA"39 value += 140 lblOutput.Text &= vbCrLf & "local variable " & _41 "value in MethodA is " & value & " before exiting MethodA"42 End Sub ' MethodA43 44 ' uses instance variable value45 Sub MethodB()46 lblOutput.Text &= vbCrLf & vbCrLf & "instance variable" & _47 " value is " & value & " after entering MethodB"48 value *= 1049 lblOutput.Text &= vbCrLf & "instance variable " & _50 "value is " & value & " before exiting MethodB"51 End Sub ' MethodB52 53 End Class ' FrmScoping

When MethodB procedure refers to variable value, the instance variable value (line 12) is used.

Page 37: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

37

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)

• The current time of day becomes the seed value for the calculation

• 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

Page 38: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline38

RandomInteger.vb

1 ' Fig. 6.14: RandomInteger.vb2 ' Generating random integers.3 4 Imports System.Windows.Forms5 6 Module modRandomInteger7 8 Sub Main()9 Dim randomObject As Random = New Random()10 Dim randomNumber As Integer11 Dim output As String = ""12 Dim i As Integer13 14 For i = 1 To 2015 randomNumber = randomObject.Next(1, 7)16 output &= randomNumber & " "17 18 If i Mod 5 = 0 Then ' is i a multiple of 5?19 output &= vbCrLf20 End If21 22 Next23 24 MessageBox.Show(output, "20 Random Numbers from 1 to 6", _25 MessageBoxButtons.OK, MessageBoxIcon.Information)26 End Sub ' Main27 28 End Module ' modRandomInteger

Note that we must use 7 as the second argument to produce integers in the range from 1-6

Go to the next line every time five numbers are generated

Page 39: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline39

RollDice.vb

1 ' Fig. 6.15: RollDice.vb2 ' Rolling four dice.3 4 Imports System.IO5 6 Public Class FrmRollDice7 Inherits System.Windows.Forms.Form8 9 ' button for rolling dice10 Friend WithEvents cmdRoll As System.Windows.Forms.Button11 12 ' labels to display die images13 Friend WithEvents lblDie1 As System.Windows.Forms.Label14 Friend WithEvents lblDie2 As System.Windows.Forms.Label15 Friend WithEvents lblDie3 As System.Windows.Forms.Label16 Friend WithEvents lblDie4 As System.Windows.Forms.Label17 18 ' Visual Studio .NET generated code19 20 ' declare Random object reference21 Dim randomNumber As Random = New Random()22 23 ' display results of four rolls24 Private Sub cmdRoll_Click(ByVal sender As System.Object, _25 ByVal e As System.EventArgs) Handles cmdRoll.Click26 27 ' method randomly assigns a face to each die28 DisplayDie(lblDie1)29 DisplayDie(lblDie2)30 DisplayDie(lblDie3)31 DisplayDie(lblDie4)32 End Sub ' cmdRoll_Click33

Event-handling method cmdRoll_Click, executes whenever the user clicks cmdRoll

RandomNumber is an instance variable of FrmRollDice. This allows the same Random object to be used each time DisplayDie executes

Page 40: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline40

RollDice.vb

34 ' get a random die image35 Sub DisplayDie(ByVal dieLabel As Label)36 37 ' generate random integer in range 1 to 638 Dim face As Integer = randomNumber.Next(1, 7)39 40 ' load corresponding image41 dieLabel.Image = Image.FromFile( _42 Directory.GetCurrentDirectory & "\Images\die" & _43 face & ".png")44 End Sub ' DisplayDie45 46 End Class ' FrmRollDice

Image property displays an image on the labelClass Image is contained in the System.Drawing namespace, which is imported by default in all Windows Applications

Method Directory.GetCurrentDirectory returns the location of the folder in which the current project is located, including bin

Page 41: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline41

RollTwelveDice.vb

1 ' Fig. 6.16: RollTwelveDice.vb2 ' Rolling 12 dice with frequency chart.3 4 Imports System.IO5 6 Public Class FrmRollTwelveDice7 Inherits System.Windows.Forms.Form8 9 ' labels to display die images10 Friend WithEvents lblDie1 As System.Windows.Forms.Label11 Friend WithEvents lblDie2 As System.Windows.Forms.Label12 Friend WithEvents lblDie3 As System.Windows.Forms.Label13 Friend WithEvents lblDie4 As System.Windows.Forms.Label14 Friend WithEvents lblDie5 As System.Windows.Forms.Label15 Friend WithEvents lblDie6 As System.Windows.Forms.Label16 Friend WithEvents lblDie7 As System.Windows.Forms.Label17 Friend WithEvents lblDie8 As System.Windows.Forms.Label18 Friend WithEvents lblDie9 As System.Windows.Forms.Label19 Friend WithEvents lblDie10 As System.Windows.Forms.Label20 Friend WithEvents lblDie11 As System.Windows.Forms.Label21 Friend WithEvents lblDie12 As System.Windows.Forms.Label22 23 ' displays roll frequencies24 Friend WithEvents displayTextBox As _25 System.Windows.Forms.TextBox26 27 ' Visual Studio .NET generated code28 29 ' declarations30 Dim randomObject As Random = New Random()31 Dim ones, twos, threes, fours, fives, sixes As Integer32

We declare counters for each of the possible rolls

The TextBox is used to display the cumulative frequencies of each face

Page 42: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline42

RollTwelveDice.vb

35 Private Sub cmdRoll_Click _34 (ByVal sender As System.Object, _35 ByVal e As System.EventArgs) Handles cmdRoll.Click36 37 ' assign random faces to 12 dice using DisplayDie38 DisplayDie(lblDie1)39 DisplayDie(lblDie2)40 DisplayDie(lblDie3)41 DisplayDie(lblDie4)42 DisplayDie(lblDie5)43 DisplayDie(lblDie6)44 DisplayDie(lblDie7)45 DisplayDie(lblDie8)46 DisplayDie(lblDie9)47 DisplayDie(lblDie10)48 DisplayDie(lblDie11)49 DisplayDie(lblDie12)50 51 Dim total As Integer = ones + twos + threes + fours + _52 fives + sixes53 54 Dim output As String55 56 ' display frequencies of faces57 output = "Face" & vbTab & vbTab & _58 "Frequency" & vbTab & "Percent"59 60 output &= vbCrLf & "1" & vbTab & vbTab & ones & _61 vbTab & vbTab & String.Format("{0:P}", ones / total)62 63 output &= vbCrLf & "2" & vbTab & vbTab & twos & vbTab & _64 vbTab & String.Format("{0:P}", twos / total)65 66 output &= vbCrLf & "3" & vbTab & vbTab & threes & vbTab & _67 vbTab & String.Format("{0:P}", threes / total)

The “P” format code is used to display the frequency of each roll as percentages

Page 43: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline43

RollTwelveDice.vb

68 69 output &= vbCrLf & "4" & vbTab & vbTab & fours & vbTab & _70 vbTab & String.Format("{0:P}", fours / total)71 72 output &= vbCrLf & "5" & vbTab & vbTab & fives & vbTab & _73 vbTab & String.Format("{0:P}", fives / total)74 75 output &= vbCrLf & "6" & vbTab & vbTab & sixes & vbTab & _76 vbTab & String.Format("{0:P}", sixes / total) & vbCrLf77 78 displayTextBox.Text = output79 End Sub ' cmdRoll_Click80 81 ' display a single die image82 Sub DisplayDie(ByVal dieLabel As Label)83 84 Dim face As Integer = randomObject.Next(1, 7)85 86 dieLabel.Image = _87 Image.FromFile(Directory.GetCurrentDirectory & _88 "\Images\die" & face & ".png")89 90 ' maintain count of die faces91 Select Case face92 93 Case 194 ones += 195 96 Case 297 twos += 198 99 Case 3100 threes += 1101

Select Case is used to calculate the frequency

Page 44: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline44

RollTwelveDice.vb

102 Case 4103 fours += 1104 105 Case 5106 fives += 1107 108 Case 6109 sixes += 1110 111 End Select112 113 End Sub ' DisplayDie114 115 End Class ' FrmRollTwelveDice

Page 45: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

45

6.13 Example: Game of Chance

• Craps– The next application simulates one of the most popular

games of chance

– The player must roll two dice on the first and all subsequent rolls

Page 46: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline46

CrapsGame.vb

1 ' Fig 6.17: CrapsGame.vb2 ' Playing a craps game.3 4 Imports System.IO5 6 Public Class FrmCrapsGame7 Inherits System.Windows.Forms.Form8 9 Friend WithEvents cmdRoll As Button ' rolls dice10 Friend WithEvents cmdPlay As Button ' starts new game11 12 ' dice displayed after each roll13 Friend WithEvents picDie1 As PictureBox14 Friend WithEvents picDie2 As PictureBox15 16 ' pointDiceGroup groups dice representing player's point17 Friend WithEvents pointDiceGroup As GroupBox18 Friend WithEvents picPointDie1 As PictureBox19 Friend WithEvents picPointDie2 As PictureBox20 21 Friend WithEvents lblStatus As Label22 23 ' Visual Studio .NET generated code24 25 ' die-roll constants26 Enum DiceNames27 SNAKE_EYES = 228 TREY = 329 CRAPS = 730 YO_LEVEN = 1131 BOX_CARS = 1232 End Enum33

A GroupBox is a container used to group related components

Enumerations are used to define groups of related constants

Page 47: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline47

CrapsGame.vb

34 ' file-name and directory constants35 Const FILE_PREFIX As String = "/images/die"36 Const FILE_SUFFIX As String = ".png"37 38 Dim myPoint As Integer39 Dim myDie1 As Integer40 Dim myDie2 As Integer41 Dim randomObject As Random = New Random()42 43 ' begins new game and determines point44 Private Sub cmdPlay_Click(ByVal sender As System.Object, _45 ByVal e As System.EventArgs) Handles cmdPlay.Click46 47 ' initialize variables for new game48 myPoint = 049 pointDiceGroup.Text = "Point"50 lblStatus.Text = ""51 52 ' remove point-die images53 picPointDie1.Image = Nothing54 picPointDie2.Image = Nothing55 56 Dim sum As Integer = RollDice()57 58 ' check die roll59 Select Case sum60 61 Case DiceNames.CRAPS, DiceNames.YO_LEVEN62 63 ' disable roll button64 cmdRoll.Enabled = False65 lblStatus.Text = "You Win!!!"66

Keyword Const creates a single constant identifier in which values cannot be modified after they are declared

Keyword Nothing can be used with reference-type variables to specify that no object is associated with the variable

Setting the Image property to Nothing causes the PictureBoxes to appear blank

The Select structure analyzes the roll returned by RollDice to determine how play should continue

Page 48: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline48

CrapsGame.vb

67 Case DiceNames.SNAKE_EYES, _68 DiceNames.TREY, DiceNames.BOX_CARS69 70 cmdRoll.Enabled = False71 lblStatus.Text = "Sorry. You Lose."72 73 Case Else74 myPoint = sum75 pointDiceGroup.Text = "Point is " & sum76 lblStatus.Text = "Roll Again!"77 DisplayDie(picPointDie1, myDie1)78 DisplayDie(picPointDie2, myDie2)79 cmdPlay.Enabled = False80 cmdRoll.Enabled = True81 82 End Select83 84 End Sub ' cmdPlay_Click85 86 ' determines outcome of next roll87 Private Sub cmdRoll_Click(ByVal sender As System.Object, _88 ByVal e As System.EventArgs) Handles cmdRoll.Click89 90 Dim sum As Integer = RollDice()91 92 ' check outcome of roll93 If sum = myPoint Then94 lblStatus.Text = "You Win!!!"95 cmdRoll.Enabled = False96 cmdPlay.Enabled = True97 ElseIf sum = DiceNames.CRAPS Then98 lblStatus.Text = "Sorry. You Lose."99 cmdRoll.Enabled = False100 cmdPlay.Enabled = True101 End If

Disabling a Button causes no action to be performed when the Button is clicked

Page 49: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline49

CrapsGame.vb

102 103 End Sub ' cmdRoll_Click104 105 ' display die image106 Sub DisplayDie(ByVal picDie As PictureBox, _107 ByVal face As Integer)108 109 ' assign die image to picture box110 picDie.Image = _111 Image.FromFile(Directory.GetCurrentDirectory & _112 FILE_PREFIX & face & FILE_SUFFIX)113 End Sub ' DisplayDie114 115 ' generate random die rolls116 Function RollDice() As Integer117 Dim die1, die2 As Integer118 119 ' determine random integer120 die1 = randomObject.Next(1, 7)121 die2 = randomObject.Next(1, 7)122 123 ' display rolls124 DisplayDie(picDie1, die1)125 DisplayDie(picDie2, die2)126 127 ' set values128 myDie1 = die1129 myDie2 = die2130 131 Return die1 + die2132 End Function ' RollDice133 134 End Class ' FrmCrapsGame

RollDice generates two random numbers and calls method DisplayDie, which loads an appropriate die image on the PictureBox passed to it.

Page 50: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline50

CrapsGame.vb

GroupBox PictureBoxes (displaying images)

Page 51: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

51

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

Page 52: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

52

6.14 Recursion

Fig. 6.18 Recursive evaluation of 5!.

5!

5 * 4!

4 * 3!

3 * 2!

2 * 1!

1

5!

5 * 4!

4 * 3!

3 * 2!

2 * 1!

1

Final value = 120

5! = 5 * 24 = 120 is returned

4! = 4 * 6 = 24 is returned

3! = 3 * 2 = 6 is returned

2! = 2 * 1 = 2 is returned

1 returned

(a) Procession of recursive calls

(b) Values returned from each recursive call

Page 53: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline53

Factorial.vb

1 ' Fig. 6.19: Factorial.vb2 ' Calculating factorials using recursion.3 4 Public Class FrmFactorial5 Inherits System.Windows.Forms.Form6 7 Friend WithEvents lblEnter As Label ' prompts for Integer8 Friend WithEvents lblFactorial As Label ' indicates output9 10 Friend WithEvents txtInput As TextBox ' reads an Integer11 Friend WithEvents txtDisplay As TextBox ' displays output12 13 Friend WithEvents cmdCalculate As Button ' generates output14 15 ' Visual Studio .NET generated code16 17 Private Sub cmdCalculate_Click(ByVal sender As System.Object, _18 ByVal e As System.EventArgs) Handles cmdCalculate.Click19 20 Dim value As Integer = Convert.ToInt32(txtInput.Text)21 Dim i As Integer22 Dim output As String23 24 txtDisplay.Text = ""25 26 For i = 0 To value27 txtDisplay.Text &= i & "! = " & Factorial(i) & vbCrLf28 Next29 30 End Sub ' cmdCalculate_Click

Conversion from String to Integer

Page 54: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline54

Factorial.vb

31 32 ' recursively generates factorial of number33 Function Factorial(ByVal number As Long) As Long34 35 If number <= 1 Then ' base case36 Return 137 Else38 Return number * Factorial(number - 1)39 End If40 41 End Function ' Factorial42 43 End Class ' FrmFactorial

If number is greater than 1, a recursive call to Factorial is made with a slightly simpler problem

Forgetting to return a value from a recursive procedure can result in logic errors

Page 55: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

55

6.15 Example Using Recursion: Fibonacci Series

• The Fibonacci series– It begins with 0 and 1 and defines each subsequent Fibonacci

number as the sum of the previous two Fibonacci numbers

• Golden ratio– The ratio of successive fibonacci numbers converges on a

constant value near 1.618

• Fibonacci method– Each invocation of the method that does not match one of

the base cases results in two additional recursive calls to the method

– Fibonacci value of 30 requires 2,692,537

Page 56: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline56

Fibonacci.vb

1 ' Fig. 6.20: Fibonacci.vb2 ' Demonstrating Fibonacci sequence recursively.3 4 Public Class FrmFibonacci5 Inherits System.Windows.Forms.Form6 7 Friend WithEvents lblPrompt As Label ' prompts for input8 Friend WithEvents lblResult As Label ' displays result9 10 Friend WithEvents cmdCalculate As Button ' calculates result11 12 Friend WithEvents txtInputBox As TextBox ' reads an Integer13 14 ' Visual Studio .NET generated code15 16 ' displays Fibonacci number in txtInputBox17 Private Sub cmdCalculate_Click(ByVal sender As System.Object, _18 ByVal e As System.EventArgs) Handles cmdCalculate.Click19 20 ' read input21 Dim number As Integer = Convert.ToInt32(txtInputBox.Text)22 23 lblResult.Text = "Fibonacci Value is " & Fibonacci(number)24 End Sub ' cmdCalculate_Click25 26 ' calculate Fibonacci value recusively 27 Function Fibonacci(ByVal number As Integer) As Long28 29 ' check for base cases30 If number = 1 OrElse number = 0 Then31 Return number32 Else33 Return Fibonacci(number - 1) + Fibonacci(number - 2)34 End If35

This call to Fibonacci is not a recursive call

If number is greater than 1, the recursion step generates two recursive calls

Page 57: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline57

Fibonacci.vb

36 End Function ' Fibonacci37 38 End Class ' FrmFibonacci

Page 58: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

58

6.15 Example Using Recursion: Fibonacci Series

Fig. 6.21 Recursive calls to method Fibonacci (abbreviated as F).

Fibonacci( 3 )

Fibonacci( 2 ) Fibonacci( 1 )

Fibonacci( 0 )Fibonacci( 1 ) return 1

return

return 1 return 0

return

Page 59: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

59

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

Page 60: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

60

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

Page 61: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline61

Overload.vb

1 ' Fig. 6.22: Overload.vb2 ' Using overloaded methods.3 4 Public Class FrmOverload5 Inherits System.Windows.Forms.Form6 7 Friend WithEvents outputLabel As Label8 9 ' Visual Studio .NET generated code10 11 Private Sub FrmOverload_Load(ByVal sender As System.Object, _12 ByVal e As System.EventArgs) Handles MyBase.Load13 14 outputLabel.Text = "The square of Integer 7 is " & _15 square(7) & vbCrLf & "The square of Double " & _16 "7.5 is " & square(7.5)17 End Sub ' FrmOverload_Load18 19 Function Square(ByVal value As Integer) As Integer20 Return Convert.ToInt32(value ^ 2)21 End Function ' Square22 23 Function Square(ByVal value As Double) As Double24 Return value ^ 225 End Function ' Square26 27 End Class ' FrmOverload

The compiler uses a logical name to differ between the two Square methods

The compiler might use the logical name “Square of Integer”

“Square of Double” for the Square method that specifies a Double parameter

Page 62: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline62

Overload2.vb

1 ' Fig. 6.23: Overload2.vb2 ' Using overloaded procedures with identical signatures and3 ' different return types.4 5 Public Class FrmOverload26 Inherits System.Windows.Forms.Form7 8 Friend WithEvents outputLabel As Label9 10 ' Visual Studio .NET generated code11 12 Private Sub FrmOverload2_Load(ByVal sender As System.Object, _13 ByVal e As System.EventArgs) Handles MyBase.Load14 15 outputLabel.Text = "The square of Integer 7 is " & _16 square(7) & vbCrLf & "The square of Double " & _17 "7.5 is " & square(7.5)18 End Sub ' FrmOverload2_Load19 20 Function Square(ByVal value As Double) As Integer21 Return Convert.ToInt32(value ^ 2)22 End Function ' Square23 24 Function Square(ByVal value As Double) As Double25 Return value ^ 226 End Function ' Square27 28 End Class ' FrmOverload2

Procedure calls cannot be distinguished by return type

Page 63: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline63

Overload2.vb

Program Output

The creating of overloaded procedures with identical parameter lists and different return types produces a syntax error

Page 64: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

64

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

Page 65: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline65

Power.vb

1 ' Fig 6.24 Power.vb2 ' Calculates the power of a value, defaults to square.3 4 Public Class FrmPower5 Inherits System.Windows.Forms.Form6 7 Friend WithEvents txtBase As TextBox ' reads base8 Friend WithEvents txtPower As TextBox ' reads power9 10 Friend WithEvents inputGroup As GroupBox11 12 Friend WithEvents lblBase As Label ' prompts for base13 Friend WithEvents lblPower As Label ' prompts for power14 Friend WithEvents lblOutput As Label ' displays output15 16 Friend WithEvents cmdCalculate As Button ' generates output17 18 ' Visual Studio .NET generated code19 20 ' reads input and displays result21 Private Sub cmdCalculate_Click(ByVal sender As System.Object, _22 ByVal e As System.EventArgs) Handles cmdCalculate.Click23 24 Dim value As Integer25 26 ' call version of Power depending on power input27 If Not txtPower.Text = "" Then28 value = Power(Convert.ToInt32(txtBase.Text), _29 Convert.ToInt32(txtPower.Text))30 Else31 value = Power(Convert.ToInt32(txtBase.Text))32 End If33 34 lblOutput.Text = Convert.ToString(value)35 End Sub ' cmdCalculate_Click

Determines whether txtPower contains a value

Page 66: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline66

Power.vb

36 37 ' use iteration to calculate power38 Function Power(ByVal base As Integer, _39 Optional ByVal exponent As Integer = 2) As Integer40 41 Dim total As Integer = 142 Dim i As Integer43 44 For i = 1 To exponent45 total *= base46 Next47 48 Return total49 End Function ' Power50 51 End Class ' FrmPower

When omitted, the Optional argument defaults to the value 2

Page 67: Chapter 6 - Procedures

2002 Prentice Hall. All rights reserved.

67

6.18 Modules

• Modules– Used to group related procedures so that they can be reused

in other projects

– Similar in many ways to classes

– Should be self-contained

Page 68: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline68

DiceModule.vb

1 ' Fig. 6.25: DiceModule.vb2 ' A collection of common dice procedures.3 4 Imports System.IO5 6 Module modDice7 8 Dim randomObject As Random = New Random()9 10 ' rolls single die11 Function RollDie() As Integer12 Return randomObject.Next(1, 7)13 End Function ' RollDie14 15 ' die summation procedure16 Function RollAndSum(ByVal diceNumber As Integer) _17 As Integer18 19 Dim i As Integer 20 Dim sum As Integer = 021 22 For i = 1 To diceNumber23 sum += RollDie()24 Next25 26 Return sum27 End Function ' RollAndSum

modDice groups several dice-related procedures into a module for reuse in other programs that use dice

Page 69: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline69

DiceModule.vb

28 29 ' returns die image30 Function GetDieImage(ByVal dieValue As Integer, _31 Optional ByVal baseImageName As String = "die") _32 As System.Drawing.Image33 34 Return Image.FromFile( _35 Directory.GetCurrentDirectory & _36 "\Images\" & baseImageName & dieValue & ".png")37 End Function ' GetDieImage38 39 End Module ' modDice

Optional parameter baseImageName represents the prefix of the image name to be used

Page 70: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline70

DiceModuleTest.vb

1 ' Fig. 6.26: DiceModuleTest.vb2 ' Demonstrates modDiceModule procedures3 4 Imports System.Drawing5 6 Public Class FrmDiceModuleTest7 Inherits System.Windows.Forms.Form8 9 Friend WithEvents lblSum As Label ' displays 10-roll sum10 11 Friend WithEvents diceGroup As GroupBox12 13 ' dice images14 Friend WithEvents picDie1 As PictureBox15 Friend WithEvents picDie2 As PictureBox16 17 Friend WithEvents cmdRollDie1 As Button ' rolls blue die18 Friend WithEvents cmdRollTen As Button ' simulates 10 rolls19 Friend WithEvents cmdRollDie2 As Button ' rolls red die20 21 ' Visual Studio .NET generated code22 23 Private Sub cmdRollDie1_Click(ByVal sender As System.Object, _24 ByVal e As System.EventArgs) Handles cmdRollDie1.Click25 26 picDie1.Image = modDice.GetDieImage(modDice.RollDie())27 End Sub ' cmdRollDie1_Click28 29 Private Sub cmdRollDie2_Click(ByVal sender As System.Object, _30 ByVal e As System.EventArgs) Handles cmdRollDie2.Click31 32 picDie2.Image = modDice.GetDieImage(modDice.RollDie(), _33 "redDie")34 End Sub ' cmdRollDie2_Click35

cmdRollDie2_Click uses the Optional argument to prefix the image name and select a different image

We call procedures contained in modDice by following the module name with the dot (.) operator and the procedure name

Page 71: Chapter 6 - Procedures

2002 Prentice Hall.All rights reserved.

Outline71

DiceModuleTest.vb

36 Private Sub cmdRollTen_Click(ByVal sender As System.Object, _37 ByVal e As System.EventArgs) Handles cmdRollTen.Click38 39 lblSum.Text = Convert.ToString(modDice.RollAndSum(10))40 End Sub ' cmdRollTen_Click41 42 End Class ' FrmDiceModuleTest

This procedure sets the Text property of lblSum to the result of 10 rolls