Visual Basic - Chapter 5

Transcription

Visual Basic - Chapter 5Mohammad Shokoohi* Adopted from An Introduction to Programming Using Visual Basic 2010, Schneider1

Chapter 5 - GeneralProcedures5.1 Function Procedures5.2 Sub Procedures, Part I5.3 Sub Procedures, Part II5.4 Modular Design2

Devices for ModularityVisual Basic has two devices for breakingproblems into smaller pieces: Function procedures Sub procedures3

5.1 Function Procedures User-Defined Functions Having OneParameter User-Defined Functions Having SeveralParameters User-Defined Functions Having NoParameters User-Defined Boolean-Valued Functions4

Some Built-In FunctionsFunction: IntExample: Int(2.6) is 2Input: numberOutput: numberFunction: Math.RoundExample: Math.Round(1.23, 1) is 1.2Input: number, numberOutput: number5

Some Built-In Functions(continued)Function: FormatPercentExample: FormatPercent(0.12, 2) is 12.00%Input: number, numberOutput: stringFunction: FormatNumberExample: FormatNumber(12.62, 1) is 12.6Input: number, numberOutput: string6

Function Procedures Function procedures (aka user-definedfunctions) always return one value Syntax:Function FunctionName(ByVal var1 As Type1,ByVal var2 As Type2,.) As ReturnDataTypestatement(s)Return expressionEnd Function7

Example With One ParameterFunction FtoC(ByVal t As Double) As Double'Convert Fahrenheit temp to CelsiusReturn (5 / 9) * (t - 32)End Function8

Header of the FtoCFunction Procedure9

Example 1: FormtxtTempFtxtTempC10

Example 1: CodePrivate Sub btnConvert Click(.)Handles btnConvert.ClickDim fahrenheitTemp, celsiusTemp As DoublefahrenheitTemp CDbl(txtTempF.Text)celsiusTemp FtoC(fahrenheitTemp)txtTempC.Text CStr(celsiusTemp )End SubFunction FtoC(ByVal t As Double) As DoubleReturn (5 / 9) * (t - 32)End Function11

Example 1: Output12

Example With One ParameterFunction FirstName(ByVal fullName AsString) As String'Extract first name from full nameDim firstSpace As IntegerfirstSpace fullName.IndexOf(" ")Return fullName.Substring(0, firstSpace)End Function13

Example 2: FormtxtFullNametxtFirstName14

Example 2: CodePrivate Sub btnDetermine Click(.)Handles btnDetermine.ClickDim fullName As StringfullName txtFullName.TexttxtFirstName.Text FirstName(fullName)End SubFunction FirstName(ByVal fullName As String)As StringDim firstSpace As IntegerfirstSpace name.IndexOf(" ")Return name.Substring(0, firstSpace)End Function15

Example 2: Output16

User-Defined Function HavingSeveral ParametersFunction Pay(ByVal wage As Double,ByVal hrs As Double) As DoubleDim amt As Double 'amount of salarySelect Case hrsCase Is 40amt wage * hrsCase Is 40amt wage * 40 (1.5 * wage * (hrs – 40))End SelectReturn amtEnd Function17

Example 3: FormtxtWagetxtHourstxtEarnings18

Example 3: Partial CodePrivate Sub btnCalculate Click(.)Handles btnCalculate.ClickDim hourlyWage, hoursWorkded As DoublehourlyWage CDbl(txtWage.Text)hoursWorked CDbl(txtHours.Text)txtEarnings.Text FormatCurrency(Pay(hourlyWage, hoursWorked))End SubFunction call19

Example 3: Output20

User-Defined Function HavingNo ParametersFunction CostOfItem() As DoubleDim price As Double CDbl(txtPrice.Text)Dim quantity As Integer CDbl(txtQuantity.Text)Dim cost price * quantityReturn costEnd Function21

User-Defined Boolean-ValuedFunctionFunction IsVowelWord(ByVal word As String) AsBooleanIf word.IndexOf("A") -1 ThenReturn FalseEnd If.If word.IndexOf("U") -1 ThenReturn FalseEnd IfReturn TrueEnd Function22

5.2 Sub Procedures, Part I Defining and Calling Sub Procedures Variables and Expressions as Arguments Sub Procedures Calling Other SubProcedures23

General Form of SubProcedure24

Calling a Sub Procedure The statement that invokes a Subprocedure is referred to as a callingstatement. A calling statement looks like this:ProcedureName(arg1, arg2,., argN)25

Naming Sub ProceduresThe rules for naming Sub procedures arethe same as the rules for naming variables.26

Passing ValuesDisplaySum(2, 3)Sub DisplaySum(ByVal num1 As Double, ByVal num2As Double)Dim z As Doublez num1 num2lstOutput.Items.Add("The sum of " & num1 &" and " & num2 & " is " & z & ".")End Sub In the Sub procedure, 2 will be stored in num1and 3 will be stored in num227

Arguments and ParametersSum(2, 3)argumentsparametersSub DisplaySum(ByVal num1 As Double, ByVal num2As Double)displayedautomatically28

Several Calling StatementsDisplaySum(2, 3)DisplaySum(4, 6)DisplaySum(7, 8)Output:The sum of 2 and 3 is 5.The sum of 4 and 6 is 10The sum of 7 and 8 is 15.29

Passing Strings and NumbersDemo("CA", 38)Sub Demo(ByVal state As String, ByVal popAs Double)lstOutput.Items.Add state &" has population " & pop & " million."End SubNote: The statement Demo(38, "CA") would not bevalid. The types of the arguments must be in thesame order as the types of the parameters.30

Variables and Expressions asArgumentsDim s As String "CA"Dim p As Double 19Demo(s, 2 * p)Sub Demo(ByVal state As String, ByVal popAs Double)lstOutput.Items.Add state &" has population " & pop & " million."End SubNote: The argument names need not match theparameter names. For instance, s versus state.31

Sub Procedure Having NoParametersSub ("This program displays")lstBox.Items.Add("the name and population")lstBox.Items.Add("of a state.")End Sub32

Sub Procedure Calling AnotherSub ProcedurePrivate Sub btnDisplay Click(.) HandlesbtnDisplay.ClickDemo("CA", 37)End SubSub Demo(ByVal state As String, ByVal popAs put.Items.Add state &" has population " & pop & " million."End Sub33

OutputThis program displaysthe name and populationof a state.CA has population 37 million.34

5.3 Sub Procedures, Part II Passing by Value Passing by Reference Sub Procedures that Return a SingleValue Lifetime and Scope of Variables andConstants Debugging35

ByVal and ByRef Parameters in Sub procedure headersare proceeded by ByVal or ByRef ByVal stands for By Value ByRef stands for By Reference36

Passing by Value When a variable argument is passed to aByVal parameter, just the value of theargument is passed. After the Sub procedure terminates, thevariable has its original value.37

ExamplePublic Sub btnOne Click (.) HandlesbtnOne.ClickDim n As Double 4Triple(n)txtBox.Text CStr(n)End SubSub Triple(ByVal num As Double)num 3 * numEnd SubOutput:438

Same Example: n numPublic Sub btnOne Click (.) HandlesbtnOne.ClickDim num As Double 4Triple(num)txtBox.Text CStr(num)End SubSub Triple(ByVal num As Double)num 3 * numEnd SubOutput:439

Passing by Reference When a variable argument is passed to aByRef parameter, the parameter is giventhe same memory location as theargument. After the Sub procedure terminates, thevariable has the value of the parameter.40

ExamplePublic Sub btnOne Click (.) HandlesbtnOne.ClickDim num As Double 4Triple(num)txtBox.Text CStr(num)End SubSub Triple(ByRef num As Double)num 3 * numEnd SubOutput:1241

Example: numnPrivate Sub btnOne Click(.) HandlesbtnOne ClickDim n As Double 4Triple(n)txtBox.Text CStr(n)End SubSub Triple(ByRef num As Double)num 3 * numEnd SubOutput:1242

Most Common Use of ByRef:Get InputSub InputData(ByRef wage As Double,ByRef hrs As Double)wage CDbl(txtWage.Text)hrs CDbl(txtHours.Text)End Sub43

Sub Procedures that Return aSingle Value with ByRef Should be avoided Usually can be replaced with a Functionprocedure44

Lifetime and Scope of aVariable Lifetime: Period during which it remains inmemory. Scope: In Sub procedures, defined same asin event procedures. Suppose a variable is declared in procedureA that calls procedure B. While procedure Bexecutes, the variable is alive, but out ofscope.45

Debugging Programs with Sub procedures areeasier to debug Each Sub procedure can be checkedindividually before being placed into theprogram46

Comparing Function Procedureswith Sub Procedures Sub procedures are accessed using acalling statement Functions are called where you wouldexpect to find a literal or expression For example: result functionCall lstBox.Items.Add (functionCall)47

Functions vs. Procedures Both can perform similar tasks Both can call other procedures Use a function when you want to returnone and only one value48

5.4 Modular Design Top-Down Design Structured Programming Advantages of Structured Programming49

Design Terminology Large programs can be broken downinto smaller problems divide-and-conquer approach calledstepwise refinement Stepwise refinement is part of topdown design methodology50

Top-Down Design General problems are at the top of thedesign Specific tasks are near the end of thedesign Top-down design and structuredprogramming are techniques to enhanceprogrammers' productivity51

Top-Down Design Criteria1. The design should be easily readable andemphasize small module size.2. Modules proceed from general to specific asyou read down the chart.3. The modules, as much as possible, shouldbe single minded. That is, they should onlyperform a single well-defined task.4. Modules should be as independent of eachother as possible, and any relationshipsamong modules should be specified.52

Beginning of Hierarchy Chart53

Detailed Hierarchy Chart54

Structured ProgrammingControl structures in structured programming: Sequences: Statements are executed oneafter another. Decisions: One of two blocks of programcode is executed based on a test of acondition. Loops (iteration): One or more statementsare executed repeatedly as long as a specifiedcondition is true.55

Advantages of StructuredProgrammingGoal to create correct programs that areeasier to write understand modify56

Easy to Write Allows programmer to first focus on thebig picture and take care of the detailslater Several programmers can work on thesame program at the same time Code that can be used in manyprograms is said to be reusable57

Easy to Debug Procedures can be checked individually A driver program can be set up to testmodules individually before the completeprogram is ready. Using a driver program to test modules(or stubs) is known as stub testing.58

Easy to Understand Interconnections of the procedures revealthe modular design of the program. The meaningful procedure names, alongwith relevant comments, identify the tasksperformed by the modules. The meaningful procedure names help theprogrammer recall the purpose of eachprocedure.59

Easy to Change Because a structured program is selfdocumenting, it can easily bedeciphered by another programmer.60

Object-Oriented Programming an encapsulation of data and code thatoperates on the data objects have properties, respond tomethods, and raise events.61

Visual Basic - Chapter 5 Mohammad Shokoohi * Adopted from An Introduction to Programming Using Visual Basic 2010, Schneider. 2 Chapter 5 - General Procedures 5.1 Function Procedures 5.2 Sub Procedures, P