0% found this document useful (0 votes)
6 views

Ch05

Uploaded by

Melat Landuber
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Ch05

Uploaded by

Melat Landuber
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 61

Chapter 5 - General

Procedures
5.1 Function Procedures
5.2 Sub Procedures, Part I
5.3 Sub Procedures, Part II
5.4 Program Design

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
General Procedures

Visual Basic has two devices for breaking


problems into smaller pieces:
• Function procedures
• Sub procedures

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
5.1 Function Procedures

• Functions Having One Parameter


• Passing by Value
• Restriction on Data Types
• Functions Having Several Parameters
• Boolean-Valued Functions
• The Exit Function Statement

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Some Built-In Functions

Function: Int
Example: Int(2.6) is 2
Input: number
Output: number

Function: Math.Round
Example: Math.Round(1.23, 1) is 1.2
Input: number, number
Output: number
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Some Built-In Functions
(continued)
Function: Chr
Example: Chr(65) is A
Input: number
Output: string

Function: Asc
Example: Asc("Apple") is 65
Input: string
Output: number
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Function Procedures

• Function procedures (aka user-defined


functions) always return one value
• Syntax:
Function FunctionName(var1 As Type1,
var2 As Type2,
...) As ReturnDataType
statement(s)
Return expression
End Function

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example with One Parameter

Function FtoC(t As Double) As Double


'Convert Fahrenheit temp to Celsius
Return (5 / 9) * (t - 32)
End Function

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Header of the FtoC
Function Procedure

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example 1: Form

txtTempF

txtTempC

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example 1: Code
Private Sub btnConvert_Click(...) _
Handles btnConvert.Click
Dim fahrenheitTemp, celsiusTemp As Double
fahrenheitTemp = CDbl(txtTempF.Text)
celsiusTemp = FtoC(fahrenheitTemp)
txtTempC.Text = CStr(celsiusTemp )
End Sub

Function FtoC(t As Double) As Double


Return (5 / 9) * (t - 32)
End Function

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example 1: Output

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example with One Parameter

Function FirstName(fullName As String) As


String
'Extract first name from full name
Dim firstSpace As Integer
firstSpace = fullName.IndexOf(" ")
Return fullName.Substring(0, firstSpace)
End Function

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example 2: Form

txtFullName

txtFirstName

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example 2: Code
Private Sub btnDetermine_Click(...) _
Handles btnDetermine.Click
Dim fullName As String
fullName = txtFullName.Text
txtFirstName.Text = FirstName(fullName)
End Sub
Function FirstName(fullName As String) As String
Dim firstSpace As Integer
firstSpace = name.IndexOf(" ")
Return name.Substring(0, firstSpace)
End Function

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example 2: Output

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
User-Defined Function Having
Several Parameters
Function Pay(wage As Decimal,
hrs As Decimal) As Decimal
Dim amt As Decimal 'amount of salary
Select Case hrs
Case Is <= 40
amt = wage * hrs
Case Is > 40
amt = (wage * 40) +(1.5D * wage * (hrs – 40))
End Select
Return amt
End Function
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Example 3: Form

txtWage

txtHours

txtEarnings

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example 3: Partial Code
Private Sub btnCalculate_Click(...) _
Handles
btnCalculate.Click
Dim hourlyWage, hoursWorked As Decimal
hourlyWage = CDec(txtWage.Text)
hoursWorked = CDec(txtHours.Text)
txtEarnings.Text =
(Pay(hourlyWage,
hoursWorked)).ToString("C")
Function call
End Sub

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example 3: Output

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
User-Defined Boolean-Valued
Function
Function IsVowelWord(word As String) As
Boolean
If word.IndexOf("A") = -1 Then
Return False
End If
.
.
If word.IndexOf("U") = -1 Then
Return False
End If
Return True
End Function

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
The Exit Function Statement

• The Exit Function statement immediately


exits the Function procedure in which it
appears.
• Usually appears inside a decision block

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
5.2 Sub Procedures, Part I

• Defining and Calling Sub Procedures


• Variables and Expressions as Arguments
• Sub Procedures Having No Parameters
• Sub Procedures Calling Other Sub
Procedures
• The Exit Sub Statement

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
General Form of Sub
Procedure
Sub ProcedureName(par1 As Type1, par2 As Type2, _
..., parN As TypeN)
statement(s)
End Sub

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Calling a Sub Procedure

• The statement that invokes a Sub


procedure is referred to as a calling
statement.
• A calling statement looks like this:
ProcedureName(arg1, arg2,..., argN)

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Naming Sub Procedures

The rules for naming Sub procedures are


the same as the rules for naming variables.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Passing Values
DisplaySum(2, 3)
Sub DisplaySum(num1 As Double, num2 As Double)
Dim z As Double
z = num1 + num2
lstOutput.Items.Add("The sum of " & num1 &
" and " & num2 & " is " & z & ".")
End Sub

• In the Sub procedure, 2 will be stored in num1


and 3 will be stored in num2
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Arguments and Parameters

Sum(2, 3)
arguments

parameters
Sub DisplaySum(num1 As Double, num2 As Double)

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Several Calling Statements

DisplaySum(2, 3)
DisplaySum(4, 6)
DisplaySum(7, 8)

Output:
The sum of 2 and 3 is 5.
The sum of 4 and 6 is 10
The sum of 7 and 8 is 15.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Passing Strings and Numbers
Demo("CA", 39)
Sub Demo(state As String, pop As Double)

lstOutput.Items.Add = state &


" has population " & pop & " million."
End Sub

Note: The statement Demo(39, "CA") would not be


valid. The types of the arguments must be in
the same order as the types of the parameters.
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Variables and Expressions as
Arguments
Dim s As String = "CA"
Dim p As Double = 19
Demo(s, 2 * p)
Sub Demo(state As String, pop As Double)
lstOutput.Items.Add = state &
" has population " & pop & " million."
End Sub

Note: The argument names need not match the


parameter names. For instance, s versus
state. © 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Sub Procedure Having No
Parameters

Sub DescribeTask()
lstBox.Items.Clear()
lstBox.Items.Add("This program displays")
lstBox.Items.Add("the name and population")
lstBox.Items.Add("of a state.")
End Sub

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Sub Procedure Calling Another
Sub Procedure
Private Sub btnDisplay_Click(...) Handles _
btnDisplay.Click
Demo("CA", 39)
End Sub

Sub Demo(state As String, pop As Double)


DescribeTask()
lstOutput.Items.Add("")
lstOutput.Items.Add = state &
" has population " & pop & " million."
End Sub

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Output

This program displays


the name and population
of a state.

CA has population 39 million.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
5.3 Sub Procedures, Part II

• Passing by Value
• Passing by Reference
• Sub Procedures That Return a Single
Value
• Scope and Lifetime of Variables and
Constants
• Debugging

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
ByRef Keyword

• Parameters in Sub procedure headers


can be proceeded by ByRef
• ByRef stands for By Reference

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Passing by Value

• When a variable argument is passed to a


parameter not preceded with ByRef, just
the value of the argument is passed.
• After the Sub procedure terminates, the
variable has its original value.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example

Public Sub btnOne_Click (...) Handles _


btnOne.Click
Dim n As Double = 4
Triple(n)
txtBox.Text = CStr(n)
End Sub
Sub Triple(num As Double)
num = 3 * num
End Sub

Output: 4
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Same Example: n num
Public Sub btnOne_Click (...) Handles _
btnOne.Click
Dim num As Double = 4
Triple(num)
txtBox.Text = CStr(num)
End Sub
Sub Triple(num As Double)
num = 3 * num
End Sub

Output: 4
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Passing by Reference

• When a variable argument is passed to a


parameter preceded by ByRef, the
parameter is given the same memory
location as the argument.
• After the Sub procedure terminates, the
argument variable has the value of the
parameter.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Example
Public Sub btnOne_Click (...) Handles _
btnOne.Click
Dim n As Double = 4
Triple(n)
txtBox.Text = CStr(n)
End Sub
Sub Triple(ByRef num As Double)
num = 3 * num
End Sub

Output: 12
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Example: num n
Private Sub btnOne_Click(...) Handles _
btnOne_Click
Dim n As Double = 4
Triple(n)
txtBox.Text = CStr(n)
End Sub
Sub Triple(ByRef num As Double)
num = 3 * num
End Sub

Output: 12 © 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Most Common Use of ByRef:
Get Input

Sub InputData(ByRef wage As Double,


ByRef hrs As Double)
wage = CDbl(txtWage.Text)
hrs = CDbl(txtHours.Text)
End Sub

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Sub Procedures that Return a
Single Value with ByRef
• Should be avoided
• Usually can be replaced with a Function
procedure

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Lifetime and Scope of a
Variable
• Lifetime: Period during which it remains in
memory.
• Scope: In Sub procedures, defined same as
in event procedures.
• Suppose a variable is declared in procedure
A that calls procedure B. While procedure B
executes, the variable is alive, but out of
scope.
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Debugging

• Programs with Sub procedures are


easier to debug
• Each Sub procedure can be checked
individually before being placed into the
program

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Comparing Function Procedures
with Sub Procedures
• Sub procedures are accessed using a
calling statement
• Functions are called where you would
expect to find a literal or expression
• For example:
• result = functionCall
• lstBox.Items.Add (functionCall)

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Functions vs. Procedures

• Both can perform similar tasks


• Both can call other procedures
• Use a function when you want to return
one and only one value

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
5.4 Program Design

• Top-Down Design
• Structured Programming
• Advantages of Structured Programming
• Object-Oriented Programming

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Design Terminology

• Large programs can be broken down


into smaller problems
• divide-and-conquer approach called
stepwise refinement
• Stepwise refinement is part of top-
down design methodology

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Top-Down Design

• General problems are at the top of the


design
• Specific tasks are near the end of the
design
• Top-down design and structured
programming are techniques to enhance
programmers' productivity

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Top-Down Design Criteria
1. The design should be easily readable and
emphasize small module size.
2. Subtasks proceed from general to specific as you
read down the chart.
3. The subtasks, as much as possible, should be
single minded. That is, they should only perform a
single well-defined task.
4. Subtasks should be as independent of each other
as possible, and any relationships among
modules should be specified.
© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.
Beginning of Hierarchy Chart

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Detailed Hierarchy Chart

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Structured Programming

Control structures in structured programming:


• Sequences: Statements are executed one
after another.
• Decisions: One of two blocks of program code
is executed based on a test of a condition.
• Loops (iteration): One or more statements are
executed repeatedly as long as a specified
condition is true.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Advantages of Structured
Programming
Goal to create correct programs that are
easier to
• write
• understand
• modify

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Easy to Write

• Allows programmer to first focus on the


big picture and take care of the details
later
• Several programmers can work on the
same program at the same time
• Code that can be used in many
programs is said to be reusable

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Easy to Debug

• Procedures can be checked individually


• A driver program can be set up to test
modules individually before the complete
program is ready.
• Using a driver program to test modules
(or stubs) is known as stub testing.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Easy to Understand

• Interconnections of the procedures reveal


the design of the program.
• The meaningful procedure names, along
with relevant comments, identify the tasks
performed by the subtasks.
• The meaningful procedure names help the
programmer recall the purpose of each
procedure.
© 2017 Pearson Education, Inc.
Hoboken, NJ. All rights reserved.
Easy to Change

• Because a structured program is self-


documenting, it can easily be
deciphered by another programmer.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
Object-Oriented Programming

• an encapsulation of data and code that


operates on the data
• Objects have properties, respond to
methods, and raise events.
• Chapter 11 discusses object-oriented
programming in detail.

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.
The Exit Sub Statement

• The Exit Sub statement immediately


exits the Sub procedure in which it
appears.
• They most commonly occur at the
beginning of a procedure to determine if
the procedure should be executed

© 2017 Pearson Education, Inc.


Hoboken, NJ. All rights reserved.

You might also like