Section 4.3. Function Procedures


[Page 169 (continued)]

4.3. Function Procedures

Visual Basic has many built-in functions. In one respect, functions are like miniature programs. They use input, they process the input, and they have output. Some functions we encountered earlier are listed in Table 4.2.

Table 4.2. Some Visual Basic built-in functions.

Function

Example

Input

Ouput

Int

Int(2.6) is 2

number

number

Chr

Chr(65) is "A"

number

string

Asc

Asc("Apple") is 65

string

number

FormatNumber

FormatNumber(12345.628, 1) is 12,345.6

number, number

string


Although the input can involve several values, the output always consists of a single value. The items inside the parentheses can be literals (as in Table 4.2), variables, or expressions.

In addition to using built-in functions, we can define functions of our own. These new functions, called Function procedures or user-defined functions, are defined in much the same way as Sub procedures and are used in the same way as built-in functions. Like built-in functions, Function procedures have a single output that can be of any data type. Function procedures can be used in expressions in exactly the same way as built-in functions. Programs refer to them as if they were literals, variables, or expressions. Function procedures are defined by function blocks of the form


[Page 170]

Function FunctionName(ByVal var1 As Type1, _                       ByVal var2 As Type2, ...) As DataType   statement(s)   Return expression End Function


The variables appearing in the top line are called parameters. Variables declared by statements inside the function block have local scope. Function names should be suggestive of the role performed and must conform to the rules for naming variables. The type DataType, which specifies the type of the output, will be one of String, Integer, Double, and so on. In the preceding general code, the next-to-last line specifies the output, which must be of type DataType. Like Sub procedures, Function procedures are typed directly into the Code window. (The last line, End Function, will appear automatically after the first line is entered into the Code window.) A variable passed to a Function procedure is normally passed by value. It can also be passed by reference and thereby possibly have its value changed by the Function procedure. However, passing a variable by reference violates good design principles, since a function is intended to only create a single result and not cause any other changes.

Two examples of Function procedures are as follows:

Function FtoC(ByVal t As Double) As Double   'Convert Fahrenheit temperature to Celsius   Return (5 / 9) * (t - 32) End Function Function FirstName(ByVal name As String) As String   'Extract the first name from a full name   Dim firstSpace As Integer   firstSpace = name.IndexOf(" ")   Return name.Substring(0, firstSpace) End Function


The value of each of the preceding functions is assigned by a statement of the form Return expression. The variables t and name appearing in the preceding functions are parameters. They can be replaced with any variable of the same type without affecting the function definition. For instance, the function FtoC could have been defined as

Function FtoC(ByVal temp As Double) As Double   'Convert Fahrenheit temperature to Celsius   Return (5 / 9) * (temp - 32) End Function



[Page 171]

Example 1.

The following program uses the function FtoC.

Object

Property

Setting

frmConvert

Text

Convert Fahrenheit to Celsius

lblTempF

Text

Temperature (Fahrenheit)

txtTempF

  

btnConvert

Text

Convert to Celsius

lblTempC

Text

Temperature (Celsius)

txtTempC

ReadOnly

True


 Private Sub btnConvert_Click(...) Handles btnConvert.Click   Dim fahrenheitTemp, celsiusTemp As Double   fahrenheitTemp = CDbl(txtTempF.Text)   celsiusTemp = FtoC(fahrenheitTemp)   txtTempC.Text = CStr(celsiusTemp)   'Note: The above four lines can be replaced with the single line   'txtTempC.Text = CStr(FtoC(CDbl(txtTempF.Text))) End Sub Function FtoC(ByVal t As Double) As Double   'Convert Fahrenheit temperature to Celsius   Return (5 / 9) * (t - 32) End Function


[Run, type 212 into the text box, and then click the button.]

Example 2.
(This item is displayed on pages 171 - 172 in the print version)

The following program uses the function FirstName.

Object

Property

Setting

frmFirstName

Text

Extract First Name

lblName

Text

Name

txtFullName

  

btnDetermine

Text

Determine First Name

txtFirstName

ReadOnly

True



[Page 172]

Private Sub btnDetermine_Click(...) Handles btnDetermine.Click   'Determine a person's first name   Dim name As String   name = txtFullName.Text   txtFirstname.Text = FirstName(name) End Sub Function FirstName(ByVal name As String) As String   'Extract the first name from a full name   Dim firstSpace As Integer   firstSpace = name.IndexOf(" ")   Return name.Substring(0, firstSpace) End Function


[Run, type Thomas Woodrow Wilson into the text box, and then click the button.]

User-Defined Functions Having Several Parameters

The input to a user-defined function can consist of one or more values. Two examples of functions with several parameters follow. One-letter variable names have been used so the mathematical formulas will look familiar and be readable. Because the names are not descriptive, the meanings of these variables are carefully spelled out in comment statements.

Function Hypotenuse(ByVal a As Double, ByVal b As Double) As Double   'Calculate the hypotenuse of a right triangle   'having sides of lengths a and b   Return Math.Sqrt(a ^ 2 + b ^ 2) End Function Function FutureValue(ByVal p As Double, ByVal r As Double, _             ByVal c As Double, ByVal n As Double) As Double   'Find the future value of a bank savings account   'p principal, the amount deposited   'r annual rate of interest   'c number of times interest is compounded per year   'n number of years   Dim i As Double  'interest rate per period   Dim m As Double  'total number of times interest is compounded   i = r / c   m = c * n   Return p * ((1 + i) ^ m) End Function



[Page 173]

Example 3.

The following program uses the Hypotenuse function.

Object

Property

Setting

frmPythagoras

Text

Right Triangle

lblSideOne

AutoSize

False

 

Text

Length of one side

txtSideOne

  

lblSideTwo

AutoSize

False

 

Text

Length of other side

txtSideTwo

  

btnCalculate

Text

Calculate Hypotenuse

lblHyp

AutoSize

False

 

Text

Length of Hypotenuse

txtHyp

ReadOnly

True


 Private Sub btnCalculate_Click(...) Handles btnCalculate.Click   'Calculate the length of the hypotenuse of a right triangle   Dim a, b As Double   a = CDbl(txtSideOne.Text)   b = CDbl(txtSideTwo.Text)   txtHyp.Text = CStr(Hypotenuse(a, b)) End Sub Function Hypotenuse(ByVal a As Double, ByVal b As Double) As Double   'Calculate the hypotenuse of a right triangle   'having sides of lengths a and b   Return Math.Sqrt(a ^ 2 + b ^ 2) End Function


[Run, type 3 and 4 into the text boxes, and then click the button.]

Example 4.
(This item is displayed on pages 173 - 175 in the print version)

The following program uses the future value function. With the responses shown, the program computes the balance in a savings account when $100 is deposited for five years at 4% interest compounded quarterly. Interest is earned four times per year at the rate of 1% per interest period. There will be 4 * 5, or 20, interest periods.


[Page 174]

Object

Property

Setting

frmBank

Text

Bank Deposit

lblAmount

Text

Amount of bank deposit:

txtAmount

  

lblRate

Text

Annual rate of interest:

txtRate

  

lblNumComp

AutoSize

False

 

Text

Number of times interest

  

is compounded per year:

txtNumComp

  

lblNumYrs

Text

Number of years:

txtNumYrs

  

btnCompute

Text

Compute Balance

lblBalance

Text

Balance:

txtBalance

ReadOnly

True


 Private Sub btnCompute_Click(...) Handles btnCompute.Click   'Find the future value of a bank deposit   Dim  p As Double   'principal, the amount deposited   Dim  r As Double   'annual rate of interest   Dim  c As Double   'number of times interest is compounded per year   Dim  n As Double   'number of years   InputData(p, r, c, n)   DisplayBalance(p, r, c, n) End Sub Sub InputData(ByRef p As Double, ByRef r As Double, _                ByRef c As Double, ByRef n As Double)       'Get the four values from the text boxes       p = CDbl(txtAmount.Text)       r = CDbl(txtRate.Text)       c = CDbl(txtNumComp.Text)       n = CDbl(txtNumYrs.Text) End Sub Sub DisplayBalance(ByVal p As Double, ByVal  r As Double, _                    ByVal c As Double, ByVal n As Double)   'Display the balance in a text box   Dim balance As Double   balance = FutureValue(p, r, c, n)   txtbalance.Text = FormatCurrency(balance) End Sub Function FutureValue(ByVal p As Double, ByVal r As Double, _                      ByVal c As Double, ByVal n As Double) As Double   'Find the future value of a bank savings account   'p  principal, the amount deposited   'r  annual rate of interest   'c  number of times interest is compounded per year   'n  number of years 
[Page 175]
Dim i As Double 'interest rate per period Dim m As Double 'total number of times interest is compounded i = r / c m = c * n Return p * ((1 + i) ^ m) End Function


[Run, type 100, .04, 4, and 5 into the text boxes, then click the button.]

User-Defined Functions Having No Parameters

Function procedures, like Sub procedures, need not have any parameters.

Example 5.

The following program uses a parameterless function.

 Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Request and display a saying   txtBox.Text = Saying() End Sub Function Saying() As String   'Retrieve a saying from the user   Return InputBox("What is your favorite saying?") End Function


[Run, click the button, and then type "Less is more." into the message box.]

The saying "Less is more." is displayed in the text box.

Comparing Function Procedures with Sub Procedures

Function procedures differ from Sub procedures in the way they are accessed. Sub procedures are invoked with call statements, whereas functions are invoked by placing them where you would otherwise expect to find a literal, variable, or expression. Unlike a Function procedure, a Sub procedure can't be used in an expression.

Function procedures can perform the same tasks as Sub procedures. For instance, they can request input and display text. However, Function procedures are primarily used to calculate a single value. Normally, Sub procedures are used to carry out other tasks.


[Page 176]

The Sub procedures considered in this book terminate only when End Sub is reached. On the other hand, Function procedures terminate as soon as the first Return statement is executed. For instance, if a Return statement is followed by a sequence of statements and the Return statement is executed, then the sequence of statements will not be executed.

Collapsing a Procedure with a Region Directive

A group of procedures or class-level variables can be collapsed behind a captioned rectangle. This task is carried out with a so-called Region directive. To specify a region, precede the code to be collapsed with a line of the form

#Region "Text to be displayed in the rectangle."

and follow the code with the line

#End Region

A tiny box holding a minus sign will appear to the left of the #Region line. To collapse the code, click on the minus sign. The code will be hidden behind a rectangle captioned with the text you specified and the minus sign will be replaced by a plus sign. Click on the plus sign to expand the region. The Region directive is used to make a program more readable or to create an outline for a program. In Figure 4.6(a), Region directives have been specified for each procedure in Example 5. In Figure 4.6(b), these two regions have been collapsed.

Figure 4.6(a). Region directives.



[Page 177]

Figure 4.6(b). Collapsed regions.


Practice Problems 4.3

1.

Suppose a program contains the lines

Dim n As Double, x As String lstOutput.Items.Add(Arc(n, x))


What types of inputs (numeric or string) and output does the function Arc have?

2.

What is displayed in the text box when btnCompute is clicked?

Private Sub btnCompute_Click(...) Handles btnCompute.Click   'How many gallons of apple cider can we make?   Dim gallonsPerBushel, apples As Double   GetData(gallonsPerBushel, apples)   DisplayNumOfGallons(gallonsPerBushel, apples) End Sub Function Cider(ByVal g As Double, ByVal x As Double) As Double   Return g * x End Function Sub DisplayNumOfGallons(ByVal galPerBu As Double, _                       ByVal apples As Double)   txtOutput.Text = "You can make "& Cider(galPerBu, apples) _                   & " gallons of cider." End Sub Sub GetData(ByRef gallonsPerBushel As Double, _            ByRef apples As Double)   'gallonsPerBushel Number of gallons of cider one bushel   'of apples makes   'apples       Number of bushels of apples available   gallonsPerBushel = 3   apples = 9 End Sub



[Page 178]
Exercises 4.3

In Exercises 1 through 10, determine the output displayed when the button is clicked.

1.

Private Sub btnConvert_Click(...) Handles btnConvert.Click   'Convert Celsius to Fahrenheit   Dim temp As Double = 95   txtOutput.Text = CStr(CtoF(temp)) End Sub Function CtoF(ByVal t As Double) As Double   Return (9 / 5) * t + 32 End Function


2.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim acres As Double 'Number of acres in a parking lot   acres = 5   txtOutput.Text = "You can park about "& Cars(acres) & " cars." End Sub Function Cars(ByVal x As Double) As Double   'Number of cars that can be parked   Return 100 * x End Function


3.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Rule of 72   Dim p As Double   p = CDbl(txtPopGr.Text) 'Population growth as a percent   txtOutput.Text = "The population will double in "& _                    DoublingTime(p) & " years." End Sub Function DoublingTime(ByVal x As Double) As Double   'Estimate time required for a population to double   'at a growth rate of x percent   Return 72 / x End Function


(Assume the text box txtPopGr contains the number 3.)

4.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Calculate max. ht. of a ball thrown straight up in the air   Dim initVel, initHt As Double   initVel = CDbl(txtVel.Text) 'Initial velocity of ball   initHt = CDbl(txtHt.Text)   'Initial height of ball   txtOutput.Text = CStr(MaximumHeight(initVel, initHt)) End Sub 
[Page 179]
Function MaximumHeight(ByVal v As Double, ByVal h As Double) _ As Double Return h + (v ^ 2 / 64) End Function


(Assume the text boxes contain the values 96 and 256.)

5.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Compute volume of a cylinder   Dim r As Double = 1   'Radius   Dim h As Double = 2   'Height   DisplayVolume(r, h)   r = 3   h = 4   DisplayVolume(r, h) End Sub Function Area(ByVal r As Double) As Double   'Compute area of a circle of radius r   Return 3.14159 * r ^ 2 End Function Sub DisplayVolume(ByVal r As Double, ByVal h As Double)   lstBox.Items.Add("Volume of cylinder having base area "& _         Area(r) & " and height "& h & " is "& (h * Area(r))) End Sub


6.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Determine the day of the week from its number   Dim days As String, num As Integer   days = "SunMonTueWedThuFriSat"   num = CInt(InputBox("Enter the number of the day."))   txtOutput.Text = "The day is "& DayOfWk(days, num) & "." End Sub Function DayOfWk(ByVal x As String, ByVal n As Integer) As String   'x String containing 3-letter abbreviations of days   'n The number of the day   Dim position As Integer   position = 3 * n - 3   Return x.Substring(position, 3) End Function


(Assume the response is 4.)

7.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Demonstrate local variables   Dim word As String = "Choo "   txtOutput.Text = TypeOfTrain() End Sub 
[Page 180]
Function TypeOfTrain() As String 'Concatenate the value of word with itself Dim word As String word &= word Return word & "train" End Function


8.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Triple a number   Dim num As Double = 5   lstOutput.Items.Add(Triple(num))   lstOutput.Items.Add(num) End Sub Function Triple(ByVal x As Double) As Double   Dim num As Double = 3   Return num * x End Function


9.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim word As String   word = "moral"   Negative(word)   word = "political"   Negative(word) End Sub Function AddA(ByVal word As String) As String   Return "a"& word   End Function Sub Negative(ByVal word As String)   lstOutput.Items.Add(word & " has the negative "& AddA(word)) End Sub


10.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim city As String, pop, shrinks As Double   Dim sr As IO.StreamReader = IO.File.OpenText("DOCS.TXT")   city = sr.ReadLine   pop = CDbl(sr.ReadLine)   shrinks = CDbl(sr.ReadLine)   DisplayData(city, pop, shrinks)   city = sr.ReadLine   pop = CDbl(sr.ReadLine)   shrinks = CDbl(sr.ReadLine)   sr.Close()   DisplayData(city, pop, shrinks) End Sub Sub DisplayData(ByVal city As String, ByVal pop As Double, _                 ByVal shrinks As Double)   lstBox.Items.Add(city & " has "& ShrinkDensity(pop, shrinks) _                     & " psychiatrists per 100,000 people.") End Sub 
[Page 181]
Function ShrinkDensity(ByVal pop As Double, _ ByVal shrinks As Double) As Double Return Int(100000 * (shrinks / pop)) End Function


(Assume the six lines of the file DOCS.TXT contain the following data: Boston, 2824000, 8602, Denver, 1633000, 3217.)

In Exercises 11 and 12, identify the errors.

11.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Select a greeting   Dim answer As Integer   answer = CInt(InputBox("Enter 1 or 2."))   txtOutput.Text = CStr(Greeting(answer)) End Sub Function Greeting(ByVal x As Integer) As Integer   Return "hellohi ya".Substring(5 * (x  1), 5)   End Function


12.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim word As String   word = InputBox("What is your favorite word?")   txtOutput.Text = "When the word is written twice, " & _                   Twice(word) & " letters are used." End Sub Function Twice(ByVal w As String) As Integer    'Compute twice the length of a string    Dim len As Integer    Return len = 2 * w.Length End Function


In Exercises 13 through 21, construct user-defined functions to carry out the primary task(s) of the program.

13.

To determine the number of square centimeters of tin needed to make a tin can, add the square of the radius of the can to the product of the radius and height of the can, and then multiply this sum by 6.283. Write a program that requests the radius and height of a tin can in centimeters as input and displays the number of square centimeters required to make the can.

14.

According to Plato, a man should marry a woman whose age is half his age plus seven years. Write a program that requests a man's age as input and gives the ideal age of his wife.

15.

The federal government developed the body mass index (BMI) to determine ideal weights. Body mass index is calculated as 703 times the weight in pounds, divided by the square of the height in inches, and then rounded to the nearest whole number. Write a program that accepts a person's weight and height as input and gives the person's body mass index. Note: A BMI of 19 to 25 corresponds to a healthy weight.


[Page 182]
16.

In order for exercise to be beneficial to the cardiovascular system, the heart rate (number of heart beats per minute) must exceed a value called the training heart rate, THR. A person's THR can be calculated from his age and resting heart rate (pulse when first awakening) as follows:

  1. Calculate the maximum heart rate as 220 age.

  2. Subtract the resting heart rate from the maximum heart rate.

  3. Multiply the result in step (b) by 60%, and then add the resting heart rate.

Write a program to request a person's age and resting heart rate as input and display their THR. (Test the program with an age of 20 and a resting heart rate of 70, and then determine your training heart rate.)

17.

The three ingredients for a serving of popcorn at a movie theater are popcorn, butter substitute, and a bucket. Write a program that requests the cost of these three items and the price of the serving as input and then displays the profit. (Test the program where popcorn costs 5 cents, butter substitute costs 2 cents, the bucket costs 25 cents, and the selling price is $5.)

18.

Rewrite the population-density program from Example 4 of Section 4.1 using a function to calculate the population density.

19.

The original cost of airmail letters was 5 cents for the first ounce and 10 cents for each additional ounce. Write a program to compute the cost of a letter whose weight is given by the user in a text box. Use a function called Ceil that rounds noninteger numbers up to the next integer. The function Ceil can be defined by Ceil(x) = Int(x).(Test the program with the weights 4, 1, 2.5, and .5 ounces.)

20.

Suppose a fixed amount of money is deposited at the beginning of each month into a savings account paying 6% interest compounded monthly. After each deposit is made, [new balance] = 1.005 * [previous balance one month ago] + [fixed amount]. Write a program that requests the fixed amount of the deposits as input and displays the balance after each of the first four deposits. A sample outcome when 800 is typed into the text box for the amount deposited each month follows.

Month 1     800.00 Month 2   1,604.00 Month 3   2,412.02 Month 4   3,224.08


21.

Write a program to request the name of a United States senator as input and display the address and greeting for a letter to the senator. Assume the name has two parts, and use a function to determine the senator's last name. A sample outcome when Robert Smith is typed into the input dialog box requesting the senator's name follows.

The Honorable Robert Smith United States Senate Washington, DC 20001 Dear Senator Smith,



[Page 183]
Solutions to Practice Problems 4.3

1.

The first argument, n, takes a value of type Double and the second argument, x, takes a String value; therefore, the input consists of a number and a string. From the two lines shown here, there is no way to determine the type of the output. This can be determined only by looking at the definition of the function.

2.

You can make 27 gallons of cider In this program, the function was called by a Sub procedure rather than by an event procedure.




An Introduction to Programming Using Visual Basic 2005
Introduction to Programming Using Visual Basic 2005, An (6th Edition)
ISBN: 0130306541
EAN: 2147483647
Year: 2006
Pages: 164

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net