Section 4.1. Sub Procedures, Part I


[Page 132]

4.1. Sub Procedures, Part I

Visual Basic has two devices, Sub procedures and Function procedures, that are used to break complex problems into small problems to be solved one at a time. To distinguish them from event procedures, Sub and Function procedures are referred to as general procedures. General procedures also eliminate repetitive code and can be reused in other programs.

In this section, we show how Sub procedures are defined and used. The programs in this section are designed to demonstrate the use of Sub procedures rather than to accomplish sophisticated programming tasks. Later chapters of the book use them for more substantial programming efforts.

A Sub procedure is a part of a program that performs one or more related tasks, has its own name, and is written as a separate part of the program. The simplest sort of Sub procedure has the form

Sub ProcedureName()   statement(s) End Sub


A Sub procedure is invoked with a statement consisting only of the name of the procedure, that is, a statement of the form

ProcedureName()


Such a statement is said to call the Sub procedure and is referred to as a call statement.

The rules for naming general procedures are identical to the rules for naming variables. The name chosen for a Sub procedure should describe the task it performs. Sub procedures are typed directly into the Code window.

Consider the following program that calculates the sum of two numbers. This program will be revised to incorporate Sub procedures.

Object

Property

Setting

frmAdd

Text

Arithmetic

btnAdd

Text

Add Numbers

lstResult

  


 Private Sub btnAdd_Click(...) Handles btnAdd.Click   'Display the sum of two numbers   Dim num1, num2 As Double   lstResult.Items.Clear()   lstResult.Items.Add("This program displays a sentence")   lstResult.Items.Add("identifying two numbers and their sum.")   lstResult.Items.Add("")   num1 = 2   num2 = 3 
[Page 133]
lstResult.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & num1 + num2 & ".") End Sub


[Run, and then click the button. The following is displayed in the list box:]

This program displays a sentence identifying two numbers and their sum. The sum of 2 and 3 is 5.


The tasks performed by this program can be summarized as follows:

Task #1: Explain purpose of program.

Task #2: Display numbers and their sum.

Sub procedures allow us to write and read a program in such a way that we first focus on the tasks and later on how to accomplish each task.

Example 1.

The following program uses a Sub procedure to accomplish the first task of the preceding program. When the statement ExplainPurpose() is reached, execution jumps to the Sub ExplainPurpose() statement. The lines between Sub ExplainPurpose() and End Sub are executed, and then execution continues with the line following the call statement.

 PrivateSub btnAdd_Click(...) Handles btnAdd.Click   'Display the sum of two numbers   Dim num1, num2 As Double   lstResult.Items.Clear()   ExplainPurpose()   lstResult.Items.Add("")   num1 = 2   num2 = 3   lstResult.Items.Add("The sum of " & num1 & " and " _                       & num2 & " is " & num1 + num2 & ".") End Sub Sub ExplainPurpose()   'Explain the task performed by the program   lstResult.Items.Add("This program displays a sentence")   lstResult.Items.Add("identifying two numbers and their sum.") End Sub


Note: When you type Sub ExplainPurpose and then press the Enter key, the editor automatically inserts the parentheses, the line End Sub, and a blank line separating the two lines of code. Also, the smart indenting feature of the editor automatically indents all lines in the block of code between the Sub and End Sub statements.

In Example 1, the btnAdd_Click event procedure is referred to as the calling procedure and the ExplainPurpose Sub procedure is referred to as the called procedure. The second task performed by the addition program also can be handled by a Sub procedure. The values of the two numbers, however, must be transmitted to the Sub procedure. This transmission is called passing.


[Page 134]

Example 2.

The following revision of the program in Example 1 uses a Sub procedure to accomplish the second task. The statement DisplaySum(2, 3) causes execution to jump to the Sub DisplaySum(ByVal num1 As Double, ByVal num2 As Double) statement, which assigns the number 2 to num1 and the number 3 to num2.

After the lines between Sub DisplaySum(ByVal num1 As Double, ByVal num2 As Double) and End Sub are executed, execution continues with the line following DisplaySum(2, 3), namely, the End Sub statement in the event procedure. Note: If you don't type in the word ByVal from the Sub DisplaySum line, the editor will automatically insert it when you either press the Enter key or move the cursor away from the line. In the next section, we consider an alternative to the keyword ByVal. For now we needn't be concerned with ByVal.

 Private Sub btnAdd_Click(...) Handles btnAdd.Click   'Display the sum of two numbers   lstResult.Items.Clear()   ExplainPurpose()   lstResult.Items.Add("")   DisplaySum(2, 3) End Sub Sub DisplaySum(ByVal num1 As Double, ByVal num2 As Double)   'Display numbers and their sum   lstResult.Items.Add("The sum of " & num1 & " and " _                       & num2 & " is " & (num1 + num2) & ".") End Sub Sub ExplainPurpose()   'Explain the task performed by the program   lstResult.Items.Add("This program displays a sentence")   lstResult.Items.Add("identifying two numbers and their sum.") End Sub


Sub procedures make a program easy to read, modify, and debug. The event procedure gives a description of what the program does, and the Sub procedures fill in the details. Another benefit of Sub procedures is that they can be called several times during the execution of the program. This feature is especially useful when there are many statements in the Sub procedure.

Example 3.
(This item is displayed on pages 134 - 135 in the print version)

The following extension of the program in Example 2 displays several sums:

 Private Sub btnAdd_Click(...) Handles btnAdd.Click   'Display the sum of two numbers   lstResult.Items.Clear() 
[Page 135]
ExplainPurpose() lstResult.Items.Add("") DisplaySum(2, 3) DisplaySum(4, 6) DisplaySum(7, 8) End Sub Sub DisplaySum(ByVal num1 As Double, ByVal num2 As Double) 'Display numbers and their sum lstResult.Items.Add("The sum of " & num1 & " and "_ & num2 & " is " & num1 + num2 & ".") End Sub Sub ExplainPurpose() 'Explain the task performed by the program lstResult.Items.Add("This program displays a sentence") lstResult.Items.Add("identifying two numbers and their sum.") End Sub


[Run, and then click the button. The following is displayed in the list box.]

This program displays sentences identifying pairs of numbers and their sums. The sum of 2 and 3 is 5. The sum of 4 and 6 is 10. The sum of 7 and 8 is 15.


The variables num1 and num2 appearing in the Sub procedure DisplaySum are called parameters. They are merely temporary place holders for the numbers passed to the Sub procedure; their names are not important. The only essentials are their type, quantity, and order. In this DisplaySum Sub procedure, the parameters must be numeric variables of type Double and there must be two of them. For instance, the Sub procedure could have been written

 Sub DisplaySum(ByVal this As Double, ByVal  that As Double)   'Display numbers and their sum   lstResult.Items.Add("The sum of " & this & " and " _                       & that & " is " & this + that & ".") End Sub


When a parameter is defined in a Sub procedure, it is automatically available to the code between the Sub and End Sub lines. That is, the code "this As Double" that defines a parameter behaves similarly to the "Dim this As Double" code that defines a variable. A string also can be passed to a Sub procedure. In this case, the receiving parameter in the Sub procedure must be followed by the type declaration "As String".

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

The following program passes a string and two numbers to a Sub procedure. When the Sub procedure is first called, the string parameter state is assigned the value "Hawaii", and the numeric parameters pop and area are assigned the values 1257608 and 6471, respectively. The Sub procedure then uses these parameters to carry out the task of calculating the population density of Hawaii. The second call statement assigns different values to the parameters.


[Page 136]

Object

Property

Setting

frmDensities

Text

4-1-4

btnDisplay

Text

Display Demographics

lstDensity

  


 Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Calculate the population densities of states   lstDensity.Items.Clear()   CalculateDensity("Hawaii", 1257608, 6471)   lstDensity.Items.Add("")   CalculateDensity("Alaska", 648818, 591000) End Sub Sub CalculateDensity(ByVal state As String, _                      ByVal pop As Double, ByVal area As Double)   Dim rawDensity, density As Double   'The density (number of people per square mile)   'will be displayed rounded one decimal place   rawDensity = pop / area   density = Math.Round(rawDensity, 1)     'Round to one decimal place   lstDensity.Items.Add("The density of " & state & " is " & density)   lstDensity.Items.Add("people per square mile.") End Sub


[Run, and then click the button. The following is displayed in the list box.]

The density of Hawaii is 194.3 people per square mile. The density of Alaska is 1.1 people per square mile. 


The parameters in the density program can have any valid variable names, as with the parameters in the addition program of Example 3. The only restriction is that the first parameter be a string variable and that the last two parameters have type Double. For instance, the Sub procedure could have been written

 Sub CalculateDensity(ByVal x As String, _                      ByVal y As Double, ByVal z As Double)   'The density (number of people per square mile)   'will be displayed rounded to a whole number 
[Page 137]
Dim rawDensity, density As Double rawDensity = y / z density = Math.Round(rawDensity, 1) 'Round to one decimal place lstDensity.Items.Add("The density of " & x & " is " & density) lstDensity.Items.Add("people per square mile.") End Sub


When nondescriptive names are used for parameters, the Sub procedure should contain comments giving the meanings of the variables. Possible comments for the preceding program are

'x    name of the state 'y    population of the state 'z    area of the state 


Variables and Expressions as Arguments

The items appearing in the parentheses of a call statement are called arguments. These should not be confused with parameters, which appear in the header of a Sub procedure. Each parameter defined for a Sub procedure corresponds to an argument passed in a call statement for that procedure. In Example 3, the arguments of the DisplaySum statements were literals. These arguments also could have been variables or expressions. For instance, the event procedure could have been written as follows. See Figure 4.1.

Figure 4.1. Passing arguments to parameters.


 Private Sub btnAdd_Click(...) Handles btnAdd.Click   'Display the sum of two numbers   Dim x, y As Double   lstResult.Items.Clear()   ExplainPurpose()   lstResult.Items.Add("")   x = 2   y = 3   DisplaySum(x, y)   DisplaySum(x + 2, 2 * y)   z = 7   DisplaySum(z, z + 1) End Sub


This feature allows values obtained as input from the user to be passed to a Sub procedure.


[Page 138]

Example 5.

The following variation of the addition program requests the two numbers as input from the user. Notice that the names of the arguments, x, and y, are different from the names of the parameters. The names of the arguments and parameters may be the same or different; what matters is that the order, number, and types of the arguments and parameters match.

Object

Property

Setting

frmAdd

Text

Add Two Numbers

lblFirstNum

Text

First Number:

txtFirstNum

  

lblSecondNum

Text

Second Number:

txtSecondNum

  

btnCompute

Text

Compute Sum

txtResult

ReadOnly

True


 Private Sub btnCompute_Click(...) Handles btnCompute.Click   'This program requests two numbers and   'displays the two numbers and their sum.   Dim x, y As Double   x = CDbl(txtFirstNum.Text)   y = CDbl(txtSecondNum.Text)   DisplaySum(x, y) End Sub Sub DisplaySum(ByVal num1 As Double, ByVal  num2 As Double)   'Display numbers and their sum   txtResult.Text = "The sum of " & num1 & " and " & num2 _                    & " is " & (num1 + num2) & "." End Sub


[Run, type 23 and 67 into the text boxes, and then click the button.]

Example 6.
(This item is displayed on pages 138 - 140 in the print version)

The following variation of Example 4 obtains its input from the file DEMOGRAPHICS.TXT. The second call statement uses different variable names for the arguments to show that using the same argument names is not necessary. See Figure 4.2.


[Page 139]

Figure 4.2. Passing arguments to parameters in Example 6.


DEMOGRAPHICS.TXT contains the following lines:

Hawaii

1257608

6471

Alaska

648818

591000

 Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Calculate the population densities of states   Dim state As String, pop, area As Double   Dim s As String, p, a As Double   Dim sr As IO.StreamReader = IO.File.OpenText("DEMOGRAPHICS.TXT")   lstDensity.Items.Clear()   state = sr.ReadLine   pop = CDbl(sr.ReadLine)   area = CDbl(sr.ReadLine)   CalculateDensity(state, pop, area)   lstDensity.Items.Add("")   s = sr.ReadLine   p = CDbl(sr.ReadLine)   a = CDbl(sr.ReadLine)   sr.Close()   CalculateDensity(s, p, a) End Sub Sub CalculateDensity(ByVal state As String, _                      ByVal pop As Double, ByVal area As Double)   'The density (number of people per square mile)   'will be displayed rounded to one decimal place   Dim rawDensity, density As Double   rawDensity = pop / area   density = Math.Round(rawDensity, 1)     'Round to one decimal place   lstDensity.Items.Add("The density of " & state & " is " & density)   lstDensity.Items.Add("people per square mile.") End Sub



[Page 140]

[Run, and then click the button. The following is displayed in the list box.]

The density of Hawaii is 194.3 people per square mile. The density of Alaska is 1.1 people per square mile. 


Sub Procedures Calling Other Sub Procedures

A Sub procedure can call another Sub procedure. If so, after the End Sub of the called Sub procedure is reached, execution continues with the line in the calling Sub procedure that follows the call statement.

Example 7.

In the following program, the Sub procedure FirstPart calls the Sub procedure SecondPart. After the statements in SecondPart are executed, execution continues with the remaining statements in the Sub procedure FirstPart before returning to the event procedure. The form contains a button and a list box.

 Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Demonstrate Sub procedure calling other Sub procedures   FirstPart()   lstOutput.Items.Add(4) End Sub Sub FirstPart()   lstOutput.Items.Add(1)   SecondPart()   lstOutput.Items.Add(3) End Sub Sub SecondPart()   lstOutput.Items.Add(2) End Sub


[Run, and click the button. The following is displayed in the list box.]

1 2 3 4


Arguments and parameters also can be used to pass values from Sub procedures back to event procedures or other Sub procedures. This important property is explored in detail in the next section.

Comments

  1. Sub procedures allow programmers to focus on the main flow of a complex task and defer the details of implementation. Modern programs use them liberally. This method of program construction is known as modular or top-down design. As a rule, a Sub procedure should perform only one task, or several closely related tasks, and should be kept relatively small.


  2. [Page 141]
  3. In this text, Sub procedure names begin with uppercase letters in order to distinguish them from variable names. Like variable names, however, they can be written with any combination of upper- and lowercase letters. Note: Parameters appearing in a Sub statement are not part of the Sub procedure name.

  4. The first line inside a Sub procedure is often a comment statement describing the task performed by the Sub procedure. If necessary, several comment statements are devoted to this purpose. Conventional programming practice also recommends that all variables used by the Sub procedure be listed in comment statements with their meanings. In this text, we give several examples of this practice, but adhere to it only when the variables are especially numerous or lack descriptive names.

  5. After a Sub procedure has been defined, Visual Basic automatically reminds you of the Sub procedure's parameters when you type in a call statement. As soon as you type in the left parenthesis of a call statement, a Parameter Info banner appears giving the names and types of the parameters. See Figure 4.3.

Figure 4.3. The Parameter Info help feature.


Practice Problems 4.1

1.

What is the difference between an event procedure and a Sub procedure?

2.

What is wrong with the following code?

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim phone As String   phone = mtxtPhoneNum.Text   AreaCode(phone) End Sub Sub AreaCode()   txtOutput.Text = "Your area code is " & phone.Substring(1, 3) End Sub 



[Page 142]
Exercises 4.1

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

1.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Quote from Kermit   Quotation()   lstOutput.Items.Add ("Kermit the frog") End Sub Sub Quotation()   'Display a quotation   lstOutput.Items.Add("Time's fun when you're having flies.") End Sub


2.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   lstOutput.Items.Add("Today")   WhatDay()   lstOutput.Items.Add("of the rest of your life.") End Sub Sub WhatDay()   lstOutput.Items.Add("is the first day") End Sub


3.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Question()   Answer() End Sub Sub Answer()   lstOutput.Items.Add("Since they were invented in the northern")   lstOutput.Items.Add("hemisphere where sundials go clockwise.") End Sub Sub Question()   lstOutput.Items.Add("Why do clocks run clockwise?")   lstOutput.Items.Add("") End Sub


4.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   FirstName()   lstOutput.Items.Add("How are you today?") End Sub Sub FirstName()   Dim name As String   name = InputBox("What is your first name?", "Name")   lstOutput.Items.Add("Hello "& name.ToUpper) End Sub


(Assume that the response is George.)


[Page 143]
5.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'The fates of Henry the Eighth's six wives   CommonFates()   lstOutput.Items.Add("died,")   CommonFates()   lstOutput.Items.Add("survived") End Sub   Sub CommonFates()   'The most common fates   lstOutput.Items.Add("divorced")   lstOutput.Items.Add("beheaded") End Sub 


6.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   lstOutput.Items.Add("a rose")   Rose()   Rose() End Sub Sub Rose()   lstOutput.Items.Add("is a rose") End Sub


7.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Good advice to follow   Advice() End Sub Sub Advice()   lstOutput.Items.Add("Keep cool, but don't freeze.")   Source() End Sub Sub Source()   lstOutput.Items.Add("Source: A jar of mayonnaise.") End Sub


8.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Answer()   Question() End Sub Sub Answer()   lstOutput.Items.Add("The answer is 9W.")   lstOutput.Items.Add("What is the question?") End Sub Sub Question()   'Note: "Wagner"is pronounced "Vagner"   lstOutput.Items.Add("Do you spell your name with a V,")   lstOutput.Items.Add("Mr. Wagner?") End Sub



[Page 144]
9.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Piano(88) End Sub Sub Piano(ByVal num As Integer)   txtOutput.Text = num & " keys on a piano" End Sub


10.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Opening line of Moby Dick   FirstLine("Ishmael") End Sub Sub FirstLine(ByVal name As String)   'Display first line   txtOutput.Text = "Call me "& name & "." End Sub


11.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Beginning of Tale of Two Cities   Times("best")   Times("worst") End Sub Sub Times(ByVal word As String)   'Display sentence   lstOutput.Items.Add("It was the "& word & " of times.") End Sub


12.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Potato(1)   Potato(2)   Potato(3)   lstOutput.Items.Add(4) End Sub Sub Potato(ByVal quantity As Integer)   lstOutput.Items.Add(quantity & " potato") End Sub


13.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Analyze a name   Dim name As String = "Gabriel"   AnalyzeName(name) End Sub Sub AnalyzeName(ByVal name As String)   'Display length and first letter   lstBox.Items.Add("Your name has "& name.Length & " letters.")   lstBox.Items.Add("The first letter is "& name.Substring(0, 1)) End Sub



[Page 145]
14.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim color As String   color = InputBox("What is your favorite color?")   Flattery(color) End Sub Sub Flattery(ByVal color As String)   txtOutput.Text = "You look dashing in "& color & "." End Sub


(Assume that the response is blue.)

15.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim num As Integer   num = CInt(InputBox("Give a number from 1 to 26."))   Alphabet(num) End Sub Sub Alphabet(ByVal num As Integer)   txtOutput.Text = "abcdefghijklmnopqrstuvwxyz".Substring(0, num) End Sub


(Assume that the response is 5.)

16.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim size As Double   size = 435   House(size)   lstOutput.Items.Add("of Representatives") End Sub Sub House(ByVal size As Double)   lstOutput.Items.Add(size & " members in the House") End Sub


17.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim num As Double   num = 144   Gross(num) End Sub Sub Gross(ByVal amount As Double)   txtOutput.Text = amount & " items in a gross" End Sub


18.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim a As String = "mile"   Acres(a) End Sub Sub Acres(ByVal length As String)   txtOutput.Text = "640 acres in a square "& length End Sub



[Page 146]
19.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim candy As String   candy = "M&M's Plain Chocolate Candies"   Brown(candy) End Sub Sub Brown(ByVal item As String)   txtOutput.Text = "30% of "& item & " are brown." End Sub


20.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim annualRate As Double = 0.08   Balance(annualRate) End Sub Sub Balance(ByVal r As Double)   Dim p As Double   p = CDbl(InputBox("What is the principal?"))   txtOutput.Text = "The balance after 1 year is "& (1 + r) * p End Sub


(Assume that the response is 100.)

21.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim hours As Double   hours = 24   Minutes(60 * hours) End Sub Sub Minutes(ByVal num As Double)   txtOutput.Text = num & " minutes in a day" End Sub


22.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim a, b As String   a = "United States"   b = "acorn"   Display(a.Substring(0, 3) & b.Substring(1, 4)) End Sub Sub Display(ByVal word As String)   txtOutput.Text = word End Sub


23.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim word As String   word = InputBox("Enter a word.")   T(word.IndexOf("t")) End Sub Sub T(ByVal num As Integer)   txtBox.Text = "t is the "& (num + 1) & "th letter of the word." End Sub


(Assume that the response is computer.)


[Page 147]
24.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim states, senators As Double   states = 50   senators = 2   Senate(states * senators) End Sub Sub Senate(ByVal num As Double)   txtBox.Text = "The number of U.S. Senators is "& num End Sub


25.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   DisplaySource()   Database("Sybase SQL Server", 75633)   Database("Oracle", 73607)   Database("Windows CE", 73375)   Database("Microsoft SQL Server", 68295) End Sub Sub DisplaySource()   lstOutput.Items.Add("A recent salary survey of readers of")   lstOutput.Items.Add("Visual Basic Programmer's Journal gave")   lstOutput.Items.Add("average salaries of database developers")   lstOutput.Items.Add("according to the database used.")   lstOutput.Items.Add("") End Sub Sub Database(ByVal db As String, ByVal salary As Double)   lstOutput.Items.Add(db & " programmers earned "& _              FormatCurrency(salary, 0) & ".") End Sub


26.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Sentence using number, thing, and place   Sentence(168, "hour", "a week")   Sentence(76, "trombone", "the big parade") End Sub Sub Sentence(ByVal num As Double, ByVal thing As String, _              ByVal where As String)   lstOutput.Items.Add(num & " "& thing & "s in "& where) End Sub


27.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim pres, college As String   Dim sr As IO.StreamReader = IO.File.OpenText("CHIEF.TXT")   pres = sr.ReadLine   college = sr.ReadLine   PresAlmaMater(pres, college)   pres = sr.ReadLine   college = sr.ReadLine 
[Page 148]
PresAlmaMater(pres, college)
sr.Close() End Sub Sub PresAlmaMater(ByVal pres As String, ByVal college As String) lstBox.Items.Add("President "& pres & " is a graduate of "_ & college & ".") End Sub


(Assume that the four lines of the file CHIEF.TXT contain the following data: Clinton, Georgetown University, Bush, Yale University.)

28.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim name As String, yob As Integer   name = InputBox("Name?")   yob = CInt(InputBox("Year of birth?"))   AgeIn2010(name, yob) End Sub Sub AgeIn2010(ByVal name As String, ByVal yob As Integer)   txtBox.Text = name & ", in the year 2010 your age will be "_         & (2010  yob) & "." End Sub


(Assume that the responses are Gabriel and 1980.)

29.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim word As String, num As Integer   word = "Visual Basic"   num = 6   FirstPart(word, num) End Sub Sub FirstPart(ByVal term As String, ByVal digit As Integer)   txtOutput.Text = "The first "& digit & " letters are "_                    & term.Substring(0, digit) & "." End Sub


30.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim statue As String, tons As Double   statue = "The Statue of Liberty"   tons = 250   HowHeavy(statue, tons) End Sub Sub HowHeavy(ByVal what As String, ByVal weight As Double)   txtOutput.Text = what & " weighs "& weight & " tons." End Sub


31.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim word As String   word = "worldly"   Negative("un" & word, word) End Sub 
[Page 149]
Sub Negative(ByVal neg As String, ByVal word As String)
txtOutput.Text = "The negative of " & word & " is " & neg End Sub


32.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim age, yrs As Integer, major As String   age = CInt(InputBox("How old are you?"))   yrs = CInt(InputBox("In how many years will you graduate?"))   major = InputBox("What sort of major do you have "& _                    "(Arts or Sciences)?")   Graduation(age + yrs, major.Substring(0, 1)) End Sub Sub Graduation(ByVal num As Integer, ByVal letter As String)   txtOutput.Text = "You will receive a B"& letter.ToUpper & _                  " degree at age "& num End Sub


(Assume that the responses are 19, 3, and arts.)

33.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   HowMany(24)   lstOutput.Items.Add("a pie.") End Sub Sub HowMany(ByVal num As Integer)   What(num)   lstOutput.Items.Add("baked in") End Sub Sub What(ByVal num As Integer)   lstOutput.Items.Add(num & " blackbirds") End Sub


34.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   txtOutput.Text = "All's"   PrintWell()   PrintWords(" that ends")   PrintWell()   txtOutput.Text &= "." End Sub Sub PrintWell()   txtOutput.Text &= " well" End Sub Sub PrintWords(ByVal words As String)   txtOutput.Text &= words End Sub



[Page 150]

In Exercises 35 through 38, find the errors.

35.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim n As Integer = 5   Alphabet() End Sub Sub Alphabet(ByVal n As Integer)   txtOutput.Text = "abcdefghijklmnopqrstuvwxyz".Substring(0, n) End Sub


36.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim word As String, number As Double   word = "seven"   number = 7   Display(word, number) End Sub Sub Display(ByVal num As Double, ByVal term As String)   txtOutput.Text = num & " "& term End Sub


37.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim name As String   name = InputBox("Name")   Handles(name) End Sub Sub Handles(ByVal moniker As String)   txtOutput.Text = "Your name is "& moniker End Sub


38.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim num As Integer = 2   Tea(num) End Sub Sub Tea()   txtOutput.Text = "Tea for "& num End Sub


In Exercises 39 through 42, rewrite the program with the output performed by a call to a Sub procedure.

39.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Display a lucky number   Dim num As Integer = 7   txtOutput.Text = num & " is a lucky number." End Sub


40.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Greet a friend   Dim name As String = "Jack"   txtOutput.Text = "Hi, "& name End Sub



[Page 151]
41.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Information about trees   Dim tree As String, ht As Double   Dim sr As IO.StreamReader = IO.File.OpenText("TREES.TXT")   lstBox.Items.Clear()   tree = sr.ReadLine   ht = CDbl(sr.ReadLine)   lstBox.Items.Add("The tallest "& tree & " in the U.S. is "_                    & ht & " feet.")   tree = sr.ReadLine   ht = CDbl(sr.ReadLine)   lstBox.Items.Add("The tallest "& tree & " in the U.S. is "_                    & ht & " feet.")   sr.Close() End Sub


(Assume that the four lines of the file TREES.TXT contain the following data: redwood, 362, pine, 223.)

42.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim city As String, salary As Double   Dim sr As IO.StreamReader = IO.File.OpenText("DATA.TXT")   lstBox.Items.Clear()   city = sr.ReadLine   salary = CDbl(sr.ReadLine)   lstBox.Items.Add("In 2000, the average salary for "& city & _                    " residents was "& FormatCurrency(salary, 0))   city = sr.ReadLine   salary = CDbl(sr.ReadLine)   lstBox.Items.Add("In 2000, the average salary for "& city & _                    " residents was "& FormatCurrency(salary, 0))   sr.Close() End Sub


(Assume that the four lines of the file DATA.TXT contain the following data: San Jose, 76076, Hartford, 42349.) Note: San Jose is located in Silicon Valley, and Hartford is the center of the insurance industry.

43.

Write a program that requests a number as input and displays three times the number. The output should be produced by a call to a Sub procedure named Triple.

44.

Write a program that requests a word as input and displays the word followed by the number of letters in the word. The output should be produced by a call to a Sub procedure named HowLong.

45.

Write a program that requests a word of at most ten letters and a width from 10 through 20 as input and displays the word right-justified in a zone having the specified width. The output should be produced by a call to a Sub procedure named PlaceNShow.

46.

Write a program that requests three numbers as input and displays the average of the three numbers. The output should be produced by a call to a Sub procedure named Average.


[Page 152]

In Exercises 47 through 50, write a program that, when btnDisplay is clicked, will display in lstOutput the output shown. The last two lines of the output should be displayed by one or more Sub procedures using data passed by variables from an event procedure.

47.

(Assume that the following is displayed.)

According to a 2004 survey of college freshmen taken by the Higher Educational Research Institute: 16 percent said they intend to major in business. 1.4 percent said they intend to major in computer science.


48.

(Assume that the current date is 12/31/2006, the label for txtBox reads "What is your year of birth?", and the user types 1980 into txtBox before btnDisplay is clicked.)

You are now 26 years old. You have lived for more than 9490 days.


49.

(Assume that the label for txtBox reads "What is your favorite number?", and the user types 7 into txtBox before btnDisplay is clicked.)

The sum of your favorite number with itself is 14. The product of your favorite number with itself is 49.


50.

(Assume that the following is displayed.)

In a recent year, 657 thousand college students took a course in Spanish 199 thousand college students took a course in French


51.

Write a program to display three verses of "Old McDonald Had a Farm." The primary verse, with variables substituted for the animals and sounds, should be contained in a Sub procedure. The program should use the file FARM.TXT. The eight lines of the file FARM.TXT contain the following data: lamb, baa, firefly, blink, computer, beep.

The first verse of the output should be

Old McDonald had a farm. Eyi eyi oh. And on his farm he had a lamb. Eyi eyi oh. With a baa baa here, and a baa baa there. Here a baa, there a baa, everywhere a baa baa. Old McDonald had a farm. Eyi eyi oh.


52.

Write a program that displays the word WOW vertically in large letters. Each letter should be drawn in a Sub procedure. For instance, the Sub procedure for the letter W follows. Hint: Use the font Courier New in the list box.

Sub DrawW()   'Draw the letter W   lstWOW.Items.Add("**          **")   lstWOW.Items.Add(" **        **")   lstWOW.Items.Add("  **  **  **")   lstWOW.Items.Add("   **    **")   lstWow.Items.Add("") End Sub



[Page 153]
53.

Write a program to display the data from Table 4.1. The occupations and numbers of jobs for 2000 and 2012 should be contained in the file GROWTH.TXT. A Sub procedure, to be called four times, should read the first three pieces of data for an occupation, calculate the percent increase from 2000 to 2012, and display the four items. Note: The percent increase is calculated as (2012 value 2000 value)/(2000 value).

Table 4.1. Occupations projected to experience the largest job growth, 20002012 (numbers in thousands of jobs).

Occupation

2000

2012

Increase

Medical assistant

365

579

59%

Home health aide

580

859

48%

Software engineer

394

573

45%

Systems analyst

468

653

40%

Source: U.S. Department of Labor.


54.

Write a program to compute tips for services rendered. The program should request the person's occupation, the amount of the bill, and the percentage tip as input and pass this information to a Sub procedure to display the person and the tip. A sample run is shown in the following figure:

Solutions to Practice Problems 4.1

1.

An event procedure always has the two parameters sender and e and ends with a phrase of the form "Handles object.event." It is triggered when the specified object experiences the specified event. On the other hand, a Sub procedure is triggered by a line of code containing the name of the Sub procedure.

2.

The statement Sub AreaCode() must be replaced by Sub AreaCode(ByVal phone As String). Whenever a value is passed to a Sub procedure, the Sub statement must provide a parameter to receive the value.




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