Create a Sub procedure

Create a Sub procedure
Dr.NaveenBansal Profile Pic
Dr.NaveenBansal,India,Teacher
Published Date:25-10-2017
Your Website URL(Optional)
Comment
CHAPTER16 I Hear You Are Breaking Up (Sub Procedures) After studying Chapter 16, you should be able to: Create a Sub procedure Call a Sub procedure Pass data by value to a procedure Pass data by reference to a procedure280 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) What’s the Proper Procedure? All of the procedures you have coded so far have been event procedures. Recall that an event procedure is a set of Visual Basic instructions that are processed when a specific event (such as the Click event) occurs. The Code Editor provides a code template for every event procedure. The code template contains the procedure’s header and footer. As you know, an event procedure’sheaderbeginswiththekeywordsPrivateSub.ThePrivatekeywordindicatesthat the procedure can be used only within the current Code Editor window. The Sub keyword is an abbreviation of the term “Sub procedure,” which is a block of code that performs a specific task. An event procedure always ends with the keywords End Sub. Figure 16-1 shows a sample Click event procedure for an Exit button. the Me.Close() statement is processed when this event occurs procedure header procedure footer Figure 16-1 Sample Click event procedure for an Exit button Event procedures are not the only Sub procedures available in Visual Basic; you also can create yourownSubprocedures.TheSubproceduresyoucreatearecalledindependentSubprocedures, because they are independent of any object and event. An independent Sub procedure is processed only when you call (invoke) it from code. But why would you want to create your own Sub procedure? First, you can use an independent Sub procedure to avoid duplicating code when differentsectionsofaprogramneedtoperformthesametask.Ratherthanenteringthesamecode in each of those sections, you can enter the code in an independent Sub procedure and then have each section call the procedure to perform its task when needed. Second, consider an event procedure that must perform many tasks. To keep the event procedure’s code from getting unwieldyanddifficulttounderstand,youcanassignsomeofthetaskstooneormoreindependent Sub procedures. Doing this makes the event procedure easer to code, because it allows the programmertoconcentrateononesmallpieceofthecodeatatime.Andfinally,independentSub procedures are used extensively in large and complex programs, which typically are written by a team of programmers. The programming team will break up the program into small and manageable tasks, and then assign some of the tasks to different team members to be coded as independentprocedures.Doingthisallowsmorethanoneprogrammertoworkontheprogramat the same time, decreasing the time it takes to write the program. Figure 16-2 shows the syntax for creating an independent Sub procedure in Visual Basic. It also includes an example of an independent Sub procedure, as well as the steps for entering an independent Sub procedure in the Code Editor window. Some programmers enter independent procedures above the first event procedure, while others enter them below the last event procedure. Still others enter them either immediately above or immediately below the procedure from which they are called. In this book, the independent procedures will usually be entered above the first event procedure in the Code Editor window. As the syntax in Figure 16-2 shows, independent Sub procedures have both a procedure header and a procedure footer. In most cases, the procedure header begins with the keywords Private Subfollowedbytheprocedurename.TherulesfornaminganindependentSubprocedurearethe same as those for naming variables; however, procedure names are usually entered using Pascal case. When using Pascal case, you capitalize the first letter in the name and the first letter of each subsequent word in the name. The procedure’s name should indicate the task the procedure performs.It is a common practice to begin the name with a verb. For example, a good name for a Sub procedure that clears the contents of the label controls in an interface is ClearLabels.281 What’s the Proper Procedure? Following the procedure name in the procedure header is a set of parentheses that contains an optional parameterList. The parameterList lists the data type and name of one or more memory locations, called parameters. The parameters store the information passed to the procedure when it is invoked. The parameters in a procedure header have procedure scope, which means they can be used only by the procedure. If the procedure does not require any information to be passed to it, as is the case with the ClearLabels procedure in Figure 16-2, an empty set of parentheses follows the procedure name in the procedure header. You will learn more about parameters later in this chapter. An independent Sub procedure ends with its procedure footer, which is always End Sub. Between the procedure header and procedure footer, you enter the instructions to be processed when the procedure is invoked. Creating an independent Sub procedure Syntax procedure header Private Sub procedureName(parameterList) statements procedure footer End Sub Example Private Sub ClearLabels() lblRegular.Text = String.Empty clears the contents of lblOvertime.Text = String.Empty the labels lblGross.Text = String.Empty End Sub Steps 1. Click a blank line in the Code Editor window. The blank line can be anywhere between the Public Class and End Class clauses. However, it must be outside any other procedure. 2. Type the Sub procedure header and then press Enter. The Code Editor automatically enters the End Sub clause for you. Figure 16-2 Syntax, example, and steps for creating an independent Sub procedure You can invoke an independent Sub procedure using the Call statement. Figure 16-3 shows the statement’s syntax and includes an example of using the statement to invoke the ClearLabels procedurefromFigure16-2.Inthesyntax, procedureNameisthenameoftheprocedureyouare calling (invoking), and argumentList (which is optional) is a comma-separated list of items, called arguments. Each argument represents an item of information that is passed to the procedure when the procedure is invoked. If you have no information to pass to the procedure that you are calling, as is the case with the ClearLabels procedure, you include an empty set of parentheses after the procedure name in the Call statement. The ClearLabels procedure is used in the Weekly Pay application, which you view in the next section. Call statement Syntax Call procedureName(argumentList) Example Call ClearLabels() Figure 16-3 Syntax and an example of the Call statement282 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) The Weekly Pay Application TheWeeklyPayapplication calculatesanddisplaysanemployee’sregularpay,overtimepay,and gross pay. Employees are paid on an hourly basis and receive time and one-half for the hours worked over 40. To open and then test the Weekly Pay application: 1. Start Visual Studio 2010 or Visual Basic 2010 Express and permanently display the Solution Explorer window. Open theWeeklyPaySolution (WeeklyPaySolution.sln) file contained in the ClearlyVB2010\Chap16\Weekly Pay Solution folder. If the designer window is not open, double-click frmMain.vb in the Solution Explorer window. 2. Start the application. Type 41 in the Hours box and then type 9 in the Rate box. Click the Calculate button. The button’s Click event procedure calculates and displays the regular pay, overtime pay, and gross pay. See Figure 16-4. Figure 16-4 Pay amounts shown in the interface 3. Change the number of hours from 41 to 4, but don’t click the Calculate button yet. Notice that the interface still shows the pay amounts for 41 hours; this is because the amounts aren’t updated until you click the Calculate button. Click the Calculate button to update the pay amounts and then click the Exit button. To avoid confusion, it would be better to remove the pay amounts from the interface whenever a change is made to either the number of hours in the txtHours control or the rate of pay in the txtRate control. You can do this by entering the following three assignment statements in each text box’s TextChanged event procedure: lblRegular.Text = String.Empty, lblOvertime.Text = String.Empty, and lblGross.Text = String.Empty. A text box’s TextChanged event occurs whenever a change is made to the contents of the text box. You also can remove the pay amounts by entering the assignment statements in an independent Sub procedure and then entering the appropriate Call statement in both TextChanged event procedures. You will use the latter approach, because entering the assignment statements in an independent Sub procedure saves you from having to enter them morethanonce. In addition,if theapplication is modified—forexample, ifthe userwantsyouto assign the string “N/A” rather than the empty string to the labels—you will need to make the change in only one place in the code. To enter the ClearLabels Sub procedure and Call statements, and then test the code: 1. Open the Code Editor window. Click the blank line below the Public Class frmMain clause and then press Enter to insert another blank line. Enter the ClearLabels procedure shown in Figure 16-5.283 What’s the Proper Procedure? enter these lines of code Figure 16-5 ClearLabels procedure 2. Open the code template for the txtHours control’s TextChanged event procedure. Enter the following Call statement: Call ClearLabels() 3. Open the code template for the txtRate control’s TextChanged event procedure. Enter the following Call statement: Call ClearLabels() 4. Save the solution and then start the application. Type 41 in the Hours box and then type 9 in the Rate box. Click the Calculate button. The pay amounts shown earlier in Figure 16-4 appear in the interface. 5. Change the number of hours from 41 to 4. Changing the number of hours causes the txtHours control’s TextChanged event to occur. As a result, the computer processes the Call ClearLabels() statement entered in the event procedure. When processing the statement, the computer temporarily leaves the event procedure to process the code contained in the ClearLabels procedure. The assignment statements in the ClearLabels procedure remove the pay amounts from the three label controls in the interface. After processing the assignment statements, the computer processes the ClearLabels procedure’s End Sub clause, which ends the procedure. The computer then returns to the txtHours control’s TextChanged event procedure and processes the line of code located below the Call statement. In this case, the line below the Call statement is End Sub, which ends the event procedure. 6. Click the Calculate button. Now change the rate of pay from 9 to 9.55. Notice that the pay amounts are removed from the interface when you make a change to the rate. Click the Calculate button and then click the Exit button. To complete the Weekly Pay application, you need to code the Clear button’s Click event procedure. The procedure should remove the contents of both text boxes, as well as the pay amounts from the three label controls. To code and then test the Clear button’s Click event procedure: 1. Open the code template for the btnClear control’s Click event procedure. Type the following comment and then press Enter twice: ' clear text boxes and label controls 2. First, you will remove the contents of the two text boxes. Enter the following assignment statements: txtHours.Text = String.Empty txtRate.Text = String.Empty 3. You can use the ClearLabels procedure to remove the pay amounts from the label controls. Enter the following Call statement: Call ClearLabels()284 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) 4. Savethe solution and thenstart the application. Type10 in the Hoursbox andthen type 5 in the Rate box. Click the Calculate button. The values 50.00, 0.00, and 50.00 appear in the label controls. 5. Click the Clear button to remove the contents of the text boxes and label controls, and then click the Exit button. Close the Code Editor window and then close the solution. Mini-Quiz 16-1 See Appendix B for the answers. 1. The items in the Call statement are referred to as . a. arguments c. passers b. parameters d. none of the above 2. Where can you enter an independent Sub procedure in the Code Editor window? a. above the Public Class clause c. below the End Class clause b. above the first event procedure d. all of the above 3. When the contents of a text box change, the text box’s event occurs. a. ChangedText c. TextModified b. ModifiedText d. TextChanged Send Me Something As mentioned earlier, an independent Sub procedure can contain one or more parameters in its procedure header; each parameter stores an item of data. The data is passed to the procedure through the argumentList in the Call statement. The number of arguments in the Call statement’s argumentList should agree with the number of parameters in the procedure’s parameterList. In addition, the data type and position of each argument should agree with the data type and position of its corresponding parameter. For example, if the first parameter has a data type of String and the second a data type of Decimal, then the first argument in the Call statement should have the String data type and the second should have the Decimal data type. This is because, when the procedure is called, the computer stores the value of the first argument in the procedure’s first parameter, the value of the second argument in the second parameter, and so on. An argument can be a constant, keyword, or variable; however, in most cases, it will be a variable. Every variable has both a value and a unique address that represents its location in the computer’s internal memory. Visual Basic allows you to pass either a copy of the variable’s value or the variable’s address to the receiving procedure. Passing a copy of the variable’s value is referred to as passing by value. Passing a variable’s address is referred to as passing by reference, and it gives the receiving procedure access to the variable in memory. The method you choose (by value or by reference) depends on whether you want to allow the receiving procedure to change the variable’s contents. Although the idea of passing information by value and by reference may sound confusing at first, itis aconcept withwhichyoualreadyarefamiliar.Toillustrate,Rob(themechanicalman)hasa savings account at a local bank. During a conversation with his friend Jerome, Rob mentions the285 Send Me Something amount of money he has in his account. Sharing this information with Jerome is similar to passing avariable by value.Knowing Rob’saccount balancedoesnot giveJeromeaccesstoRob’s bank account. It merely provides information that Jerome can use to compare to the balance in his savings account. Rob’s savings account example also provides an illustration of passing information by reference. To deposit money to or withdraw money from the account, Rob must provide the bank teller with his account number. The account number represents the location of Rob’s account at the bank and allows the teller to change the account balance. Giving the tellerthebankaccountnumberissimilartopassingavariable by reference.Theaccountnumber allows the teller to change the contents of Rob’s bank account, similar to the way a variable’s address allows the receiving procedure to change the contents of the variable. Just Give Me Its Value To pass a variable by value in Visual Basic, you include the keyword ByVal before the name of its corresponding parameter in the receiving procedure’s parameterList. When you pass a variable by value, the computer passes a copy of the variable’s contents to the receiving procedure. When only a copy of the contents is passed, the receiving procedure is not given access to the variable in memory. Therefore, it cannot change the value stored inside the variable.Itisappropriatetopassavariable by valuewhenthereceivingprocedureneedsto know the variable’s contents, but it does not need to change the contents. Unless you specify otherwise, variables in Visual Basic are automatically passed by value. The Happy Birthday application, which you code in the next set of steps, passes two variables by value to an independent Sub procedure. To code the Happy Birthday application: 1. Open the Birthday Solution (Birthday Solution.sln) file contained in the ClearlyVB2010\Chap16\Birthday Solution folder. If the designer window is not open, double-click frmMain.vb in the Solution Explorer window. When the user clicks the Display Message button, the button’s Click event procedure will prompt the user to enter a first name and an age. It then will call an independent Sub proceduretodisplaythetwoinputitemsinabirthdaymessage,likethisone: “Happy 18th Birthday, Rob”. 2. Open the Code Editor window. Locate the btnDisplay control’s Click event procedure. The code prompts the user to enter the first name and age (in years), and it stores the values in the strName and strAge variables, respectively. 3. The btnDisplay control’s Click event procedure will call an independent Sub procedure named ShowMsg to display the birthday message. The ShowMsg procedure will need to know the person’s name and age, but it will not need to change either of those values. Therefore, the event procedure will pass the ShowMsg procedure a copy of the values stored in the strName and strAge variables; in other words, the variables will be passed by value. The ShowMsg procedure will need two parameters to store the values passed to it. Because both values are strings, the parameters must have the String data type. Click the blank line below the Public Class frmMain clause and then press Enter to insert another blank line. Enter the ShowMsg procedure shown in Figure 16-6.286 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) Private Sub ShowMsg(ByVal strPerson As String, ByVal strYears As String) ' displays a message containing a name and age Dim strAddOn As String Dim intYears As Integer Integer.TryParse(strYears, intYears) Select Case intYears Case 1, 21, 31, 41, 51, 61, 71, 81, 91, 101 strAddOn = "st" enter these Case 2, 22, 32, 42, 52, 62, 72, 82, 92, 102 lines of code strAddOn = "nd" Case 3, 23, 33, 43, 53, 63, 73, 83, 93, 103 strAddOn = "rd" Case Else strAddOn = "th" End Select lblMessage.Text = "Happy " & strYears & strAddOn & " Birthday, " & strPerson & "" End Sub Figure 16-6 ShowMsg procedure 4. Next, you will enter the Call statement. Click theblankline above the EndSub clause in the btnDisplay control’s Click event procedure and then enter the following Call statement: Call ShowMsg(strName, strAge) Figure 16-7 shows the procedure header and Call statement. Notice that the number, data type, and sequence of the arguments in the Call statement match the number, data type, and sequence of the parameters in the procedure header. Also notice that the names of the arguments do not need to be identical to the names of the corresponding parameters. In fact, to avoid confusion, it usually is better to use different names for the arguments and parameters. Private Sub ShowMsg(ByVal strPerson As String, parameters ByVal strYears As String) arguments Call ShowMsg(strName, strAge) Figure 16-7 ShowMsg procedure header and Call statement Before testing the application, you will desk-check it using Rob as the name and 18 as the age. WhentheuserclickstheDisplayMessagebutton,thebutton’sClickeventprocedurecreatesthe strName and strAge variables. Next, the two InputBox functions prompt the user to enter the name and age. The functions store the name (Rob) and age (18) in the strName and strAge variables, respectively. Figure 16-8 shows the desk-check table before the Call statement is processed.287 Send Me Something strName r strAge r Rob 18 Figure 16-8 Desk-check table before the Call statement is processed Next, the Call statement invokes the ShowMsg procedure, passing it the strName and strAge variables by value.Youcantellthatthevariablesarepassed by valuebecausethekeywordByVal appears before each variable’s corresponding parameter in the ShowMsg procedure header. Passing both variables by value means that only a copy of each variable’s contents—in this case, the string “Rob” and the string “18”—is passed to the procedure. At this point, the computer temporarily leaves the btnDisplay control’s Click event procedure to process the ShowMsg procedure; the procedure header is processed first. The parameterList in the ShowMsg procedure header tells the computer to create two procedure-level String variables named strPerson and strYears. The computer stores the information passed to the procedure in those variables. In this case, it stores the string “Rob” in the strPerson variable and the string “18” in the strYears variable. Figure 16-9 shows the desk-check table after the computer processes the Call statement and ShowMsg procedure header. these variables belong to these variables belong to the btnDisplay control’s the ShowMsg procedure Click event procedure strName r strAge t strPerson r r on strYears Rob 18 Rob 18 Figure 16-9 Desk-check table after the Call statement and procedure header are processed Next, the computer processes the statements contained within the ShowMsg procedure. The Dim statements create and initialize the strAddOn and intYears variables. The TryParse method then converts the string stored in the strYears variable to an integer and stores the result in the intYears variable. Because the intYears variable contains the number 18, the Case Else clause in the Select Case statement assigns “th” to the strAddOn variable. Figure 16-10 shows the desk-check table after the Select Case statement is processed. these variables belong to the btnDisplay control’s these variables belong to Click event procedure the ShowMsg procedure strName t N strAge strPerson r n strYears strAddOn d intYears in ar Rob 18 Rob 18 th 18 Figure 16-10 Desk-check table after the Select Case statement is processed The last assignment statement in the ShowMsg procedure uses the values stored in the strPerson, strYears, and strAddOn variables to display the appropriate message. In this case, the statement displays the “Happy 18th Birthday, Rob” message. The ShowMsg procedure’s End Sub clause is processed next. At this point, the computer removes the288 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) ShowMsg procedure’s variables from internal memory, as illustrated in Figure 16-11. (Recall that a procedure-level variable is removed from the computer’s memory when the procedure in which it is declared ends.) these variables belong to the ShowMsg procedure’s the btnDisplay control’s variables are removed from Click event procedure internal memory strName t m strAge t strPerson r on strYears strAddOn r dd n intYears n Rob 18 Rob 18 th 18 Figure 16-11 Desk-check table after the ShowMsg procedure ends After the ShowMsg procedure ends, the computer returns to the line of code located below the Call statement in the btnDisplay control’s Click event procedure. In this case, it returns to the End Sub clause, which marks the end of the event procedure. When the event procedure ends, the computer removes the strName and strAge variables from internal memory. To test the Happy Birthday application: 1. Save the solution and then start the application. 2. Click the Display Message button. Type Rob and press Enter, and then type 18 and press Enter. The birthday message appears in the interface, as shown in Figure 16-12. Click the Exit button. Close the Code Editor window and then close the solution. Figure 16-12 Birthday message shown in the interface Where Do You Live? Instead of passing a copy of a variable’s value to a procedure, you can pass the variable’s address. In other words, you can pass the variable’s location in the computer’s internal memory. As you learned earlier, passing a variable’s address is referred to as passing by reference, and it gives the receiving procedure access to the variable being passed. You pass a variable by reference when you want the receiving procedure to change the contents of the variable. To pass a variable by reference in Visual Basic, you include the keyword ByRef before the name of its corresponding parameter in the receiving procedure’s parameterList. The ByRef keyword tells the computer to pass the variable’s address rather than a copy of its contents. The Total Due Calculator application, which you code in this section, provides an example of passing a variable by reference. The application’s interface and planning information are shown in Figures 16-13 and 16-14, respectively.289 Send Me Something Figure 16-13 Interface for the Total Due Calculator application Output: subtotal discount total due Input: quantity price coupon? coupon code Algorithm: 1. enter the quantity, price, and coupon? items 2. calculate the subtotal by multiplying the quantity by the price 3. if coupon?, do this: enter the coupon code if the coupon code is: do this: A05 assign 5 as the discount X25 multiply the subtotal by 10% and assign the result as the discount NE4 multiply the subtotal by 15% and assign the result as the discount Invalid assign 0 as the discount and then display an appropriate message end if otherwise, do this: assign 0 as the discount end if 4. calculate the total due by subtracting the discount from the subtotal 5. display the subtotal, discount, and total due Figure 16-14 Planning information for the Total Due Calculator application Now let’s say it is Friday afternoon and you are anxious to leave work early. Before you can do so, however, you need to code and test the Total Due Calculator application. You decide to recruit Sandy, one of your co-workers, to help you with the coding. More specifically, you ask SandytocodeStep3inthealgorithmasanindependentSubprocedure.Step3’staskistoassign the appropriate discount, so you and Sandy agree to name the procedure AssignDiscount. Both of you determine that the AssignDiscount procedure requires two items of information. First, it needs to know the value of the subtotal, because some of the discounts are based on that value. Second, it needs to know where to assign the discount. In other words, it needs to know the address of the variable that will store the discount.290 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) To code the Total Due Calculator application: 1. Open the Total Due Solution (Total Due Solution.sln) file contained in the ClearlyVB2010\Chap16\Total Due Solution folder. If the designer window is not open, double-click frmMain.vb in the Solution Explorer window. 2. Open the Code Editor window. First, you will enter the Call statement. Locate the btnCalc control’s Click event procedure. Click the blank line below the 'assigndiscount comment. The Click event procedure will need to pass a copy of the value stored in the decSubtotal variable. It also will need to pass the address of the decDiscount variable. Enter the following Call statement. (Don’t be concerned about the jagged line that appears below the arguments in the Call statement. The jagged line will disappear when you enter the procedure’s parameters in the next step.) Call AssignDiscount(decSubtotal, decDiscount) 3. Now you will enter the parameters in the AssignDiscount procedure header. The parameters will need to accept a Decimal value followed by the address of a Decimal variable. Click between the parentheses in the AssignDiscount procedure header and then type the following parameterList: ByVal decSub As Decimal, ByRef decDisc As Decimal Figure 16-15 shows both the AssignDiscount procedure and the btnCalc control’s Click event procedure. Private Sub AssignDiscount(ByVal decSub As Decimal, ByRef decDisc As Decimal) ' assigns the discount If chkCoupon.Checked = True Then Dim strCouponCode As String strCouponCode = InputBox("Coupon code:", "Coupon") Select Case strCouponCode.ToUpper Case "A05" decDisc = 5 Case "X25" decDisc = 0.1 decSub Case "NE4" decDisc = 0.15 decSub Case Else decDisc = 0 MessageBox.Show("Invalid coupon code", "Total Due Calculator", MessageBoxButtons.OK, MessageBoxIcon.Information) End Select Else decDisc = 0 End If End Sub Private Sub btnCalc_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalc.Click ' displays the subtotal, discount, and total due Figure 16-15 AssignDiscount and btnCalc Click procedures (continues)291 Send Me Something (continued) Dim intQuantity As Integer Dim decPrice As Decimal Dim decSubtotal As Decimal Dim decTotalDue As Decimal Dim decDiscount As Decimal Integer.TryParse(txtQuantity.Text, intQuantity) Decimal.TryParse(txtPrice.Text, decPrice) ' calculate subtotal decSubtotal = intQuantity decPrice ' assign discount Call AssignDiscount(decSubtotal, decDiscount) ' calculate total due decTotalDue = decSubtotal - decDiscount ' display subtotal, discount, and total due lblSubtotal.Text = decSubtotal.ToString("N2") lblDiscount.Text = decDiscount.ToString("N2") lblTotalDue.Text = decTotalDue.ToString("N2") End Sub Figure 16-15 AssignDiscount and btnCalc Click procedures Before testing the application, you will desk-check it using 4 as the quantity, 15 as the price, and X25 as the coupon code. In addition, the Coupon check box will be selected. When the user clicks the Calculate button, the btnCalc control’s Click event procedure creates the variables declared in the five Dim statements. The two TryParse methods in the procedure convert the quantity and price to the appropriate data types and then store the results in the intQuantity and decPrice variables, respectively. Next, the decSubtotal = intQuantity decPrice statement calculates the subtotal and stores the result (60) in the decSubtotal variable. Figure 16-16 shows the desk-check table before the Call statement is processed. these variables belong to the btnCalc control’s Click event procedure intQuantity n i decPrice i decSubtotal b ot decTotalDue lD decDiscount i 415 60 Figure 16-16 Desk-check table before the Call statement is processed The computer processes the Call statement next. The Call statement invokes the AssignDiscount procedure, passing it two arguments. At this point, the computer temporarily leaves the Click event procedure to process the code contained in the AssignDiscount procedure; the procedure header is processed first. The ByVal keyword before the decSub parameter indicates that the parameter is receiving a value from the Call statement. In this case, it is receiving a copy of the number stored in the decSubTotal variable. As a result, the computer createsthedecSubvariableandthenstoresthenumber60inthevariable.TheByRefkeyword292 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) before the decDisc parameter indicates that the parameter is receiving the address of a variable. When you pass a variable’s address to a procedure, the computer uses the address to locate the variable in its internal memory. It then assigns the parameter name to the memory location. In this case, the computer locates the decDiscount variable in memory and assigns the name decDisc to it. At this point, the memory location has two names: one assigned by the btnCalc control’s Click event procedure and the other assigned by the AssignDiscount procedure, as indicated in Figure 16-17. these variables belong strictly to the btnCalc control’s Click event this memory location belongs procedure to both procedures d decDisc Dis AssignDiscount intQuantity decPrice decSubtotal decTotalD an y d r b ot ot ue decDiscount d o nt btnCalc Click 415 60 this variable belongs strictly de decSub S b to the AssignDiscount procedure 60 Figure 16-17 Desk-check table after the Call statement and procedure header are processed Notice that four of the variables in Figure 16-17 belong strictly to the btnCalc control’s Click event procedure, and one belongs strictly to the AssignDiscount procedure; one memory location, however, belongs to both procedures. Although both procedures can access the memory location, each procedure uses a different name to do so. The Click event procedure uses the name decDiscount, whereas the AssignDiscount procedure uses the name decDisc. After processing the AssignDiscount procedure header, the computer processes the code contained in the procedure. For this desk-check, the Coupon check box is selected, so the computer follows the instructions in the selection structure’s true path. The first instruction createsavariablenamedstrCouponCode.Next,thestatementcontainingtheInputBoxfunction prompts the user to enter the coupon code and stores the user’s response (X25) in the strCouponCode variable. The Select Case statement is processed next. The instruction in the Case "X25" clause calculates the discount by multiplying the contents of the decSub variable (60) by 0.1. It then assigns the result (6) to the decDisc variable. Figure 16-18 shows the desk- check table after the Select Case statement is processed. Notice that when the value in the decDisc variable changes, the value in the decDiscount variable also changes. This happens because the names decDisc and decDiscount refer to the same location in the computer’s internal memory. changing the value in the decDisc variable also changes the value in the decDiscount variable decDisc d Dis AssignDiscount intQuantity decPrice decSubtotal decTotalDue an y d r b o Tot decDiscount d n btnCalc Click 415 60 6 these variables belong strictly to the AssignDiscount procedure decSub strCouponCode s rC nC d 60 X25 Figure 16-18 Desk-check table after the Select Case statement is processed293 Send Me Something The AssignDiscount procedure’s End Sub clause is processed next and ends the procedure. At this point, the computer removes the decSub and strCouponCode variables from memory. It also removes the decDisc name from the appropriate location in memory, as indicated in Figure 16-19. Notice that the decDiscount memory location now has only one name: the name assigned to it by the btnCalc control’s Click event procedure. d decDisc is AssignDiscount intQuantity decPrice decSubtotal decTotalDue Q nt y d r ub ot t d decDiscount cD ou t btnCalc Click 415 60 6 d decSub strCouponCode Co C 60 X25 Figure 16-19 Desk-check table after the AssignDiscount procedure ends After the AssignDiscount procedure ends, the computer returns to the line of code below the Call statement in the btnCalc control’s Click event procedure. In this case, it returns to the statement that calculates the total due. Figure 16-20 shows the desk-check table after the assignment statement is processed. decDisc i AssignDiscount intQuantity decPrice decSubtotal decTotalDue Q an y e Pr e ecS b o ecTo D e de decDiscount D sco n btnCalc Click 415 60 54 6 decSub u st strCouponCode C od 60 X25 Figure 16-20 Desk-check table after the total due is calculated The last three assignment statements in the Click event procedure display the contents of the decSubtotal, decDiscount, and decTotalDue variables (formatted with two decimal places) in the interface. Finally, the computer processes the Click event procedure’s End Sub clause. When the Click event procedure ends, the computer removes the procedure’s variables from memory. To test the Total Due Calculator application: 1. Save the solution and then start the application. Type 4 in the Quantity box and then type 15 in the Price box. Click the Coupon check box to select it and then click the Calculate button. 2. TypeX25 as the coupon code and then pressEnter. The correct subtotal, discount, and total due appear in the interface, as shown in Figure 16-21. Click the Exit button. Close the Code Editor window and then close the solution.294 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) Figure 16-21 Calculated amounts shown in the interface To review Mini-Quiz 16-2 what you learned about Sub See Appendix B for the answers. procedures, 1. A procedureis passedacopy of the value storedin aString variable, followed bya copy view the Ch16Sub video. of the value stored in an Integer variable. Which of the following is a valid header for the procedure? a. Private Sub Display(ByRef strX As String, For more ByRef intY As Integer) examples of Sub pro- b. Private Sub Display(ByVal strX As String, cedures, ByVal intY As Integer) see theSub c. Private Sub Display(strX As String, Proceduressectionin the intY As Integer) Ch16WantMore.pdf file. d. Private Sub Display(ByVal intX As Integer, ByRef strY As String) 2. Write a Call statement that invokes the Display procedure from Question 1. Pass the procedure a copy of the values stored in the strName and intQuantity variables. 3. In the receiving procedure’s header, you use the keyword to indicate that a variable is being passed by reference. Summary l You can create your own Sub procedures, called independent Sub procedures, in Visual Basic.IndependentSubproceduresallowprogrammerstoavoidduplicatingcodeindifferent parts of a program. They also allow the programmer to concentrate on one small piece of a program at a time. In addition, they allow a team of programmers to work on large and complex programs. l It is a common practice to begin a procedure name with a verb and to enter the name using Pascal case. l Youcan usetheCallstatement toinvokeanindependent Subprocedure. TheCallstatement allows you to pass arguments to the procedure.295 Review Questions l When calling a procedure, the number of arguments listed in the Call statement’s argumentList shouldagreewiththenumberofparameterslistedinthereceivingprocedure’s parameterList. Also, the data type and position of each argument should agree with the data type and position of its corresponding parameter. l You can pass information to an independent Sub procedure either by value or by reference. To pass a variable by value, you precede the variable’s corresponding parameter with the keyword ByVal. To pass a variable by reference, you precede the variable’s corresponding parameter with the keyword ByRef. The procedure header indicates whether a variable is being passed by value or by reference. l When you pass a variable by value, only a copy of the variable’s contents is passed. When you pass a variable by reference, the variable’s address is passed. l Variables that appear in the parameterList in a procedure header have procedure scope, which means they can be used only by the procedure. Key Terms Argument—an item listed within parentheses in a Call statement; represents information passed to the receiving procedure Call statement—the statement used to invoke an independent Sub procedure in a Visual Basic program Independent Sub procedure—a procedure that is not associated with any specific object or event and is processed only when invoked (called) from code Parameters—the memory locations listed in a procedure header Passing by reference—the process of passing a variable’s address to a procedure Passing by value—the process of passing a copy of a variable’s value to a procedure TextChanged event—occurs when a change is made to the Text property of its associated control Review Questions 1. To determine whether a variable is being passed to a procedure by value or by reference, you will need to examine . a. the Call statement b. the procedure header c. the statements entered in the procedure d. either a or b 2. Which of the following statements invokes the CalcArea Sub procedure, passing it two variables by value? a. Call CalcArea(dblLength, dblWidth) b. Call CalcArea(ByVal dblLength, ByVal dblWidth) c. Call CalcArea ByVal(dblLength, dblWidth) d. Call ByVal CalcArea(dblLength, dblWidth)296 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) 3. Which of the following is a valid header for a procedure that receives an integer followed by a number with a decimal place? a. Private Sub CalcFee(intBase As Integer, decRate As Decimal) b. Private Sub CalcFee(ByRef intBase As Integer, ByRef decRate As Decimal) c. Private Sub CalcFee(ByVal intBase As Integer, ByVal decRate As Decimal) d. Private Sub CalcFee(ByValue intBase As Integer, ByValue decRate As Decimal) 4. Which of the following statements invokes the CalcFee procedure from Review Question 3? c. Call CalcFee(intX, 25.45) a. Call CalcFee(intX, decY) d. all of the above b. Call CalcFee(2, 3.5) 5. Which of the following is false? a. The sequence of the arguments listed in the Call statement should agree with the sequence of the parameters listed in the receiving procedure’s header. b. The data type of each argument in the Call statement should match the data type of its corresponding parameter in the procedure header. c. The name of each argument in the Call statement should be identical to the name of its corresponding parameter in the procedure header. d. When you pass information to a procedure by value, the procedure stores the value of each item it receives in a separate memory location. 6. The CalcEndInventory procedure is passed four Integer variables named intBegin, intSales, intPurchases, and intEnding. The procedure should calculate the ending inventory using the beginning inventory, sales, and purchase amounts passed to the procedure. The result should be stored in the intEnding variable. Which of the following procedure headers is correct? a. Private Sub CalcEndInventory(ByVal intB As Integer, ByVal intS As Integer, ByVal intP As Integer, ByRef intFinal As Integer) b. Private Sub CalcEndInventory(ByVal intB As Integer, ByVal intS As Integer, ByVal intP As Integer, ByVal intFinal As Integer) c. Private Sub CalcEndInventory(ByRef intB As Integer, ByRef intS As Integer, ByRef intP As Integer, ByVal intFinal As Integer) d. Private Sub CalcEndInventory(ByRef intB As Integer, ByRef intS As Integer, ByRef intP As Integer, ByRef intFinal As Integer) 7. The items listed between the parentheses in a procedure header are called . a. arguments c. receivers b. parameters d. none of the above297 Exercises Exercises TRY THIS 1. Open the Bonus Solution (Bonus Solution.sln) file contained in the ClearlyVB2010\ Chap16\Bonus Solution-TRY THIS 1 folder. The application should calculate and display a bonus amount, which is based on two sales amounts entered by the user. Use the algorithm shown in Figure 16-22 to code the btnCalc control’s Click event procedure and the independent Sub procedure. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. (See Appendix B for the answer.) 1. enter sale 1 and sale 2 2. calculate the sum by adding together sale 1 and sale 2 3. if the sum is greater than 1200, do this: calculate the bonus by multiplying the sum by 10% create an independent otherwise, do this: Sub procedure that will calculate the bonus by multiplying the sum by 8% handle Steps 3 and 4 end if 4. display the bonus Figure 16-22 Algorithm for Exercise 1 TRY THIS 2. OpentheBonusSolution(BonusSolution.sln)filecontainedintheClearlyVB2010\Chap16\ Bonus Solution-TRY THIS 2 folder. The application should calculate and display a bonus amount,whichisbasedontwosalesamountsenteredbytheuser.Usethealgorithmshown inFigure16-23tocodethebtnCalccontrol’sClickeventprocedureandtheindependentSub procedure. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. (See Appendix B for the answer.) 1. enter sale 1 and sale 2 2. calculate the sum by adding together sale 1 and sale 2 3. if the sum is greater than 1200, do this: create an independent calculate the bonus by multiplying the sum by 10% Sub procedure that will otherwise, do this: handle Steps 2 and 3 calculate the bonus by multiplying the sum by 8% end if 4. display the bonus Figure 16-23 Algorithm for Exercise 2 MODIFY THIS 3. In this exercise, you modify the Total Due Calculator application coded in the chapter. Use Windows to make a copy of the Total Due Solution folder. Save the copy in the ClearlyVB2010\Chap16 folder. Rename the copy Total Due Solution-MODIFY THIS. Open the Total Due Solution (Total Due Solution.sln) file contained in the Total Due Solution-MODIFY THIS folder. Open the designer and Code Editor windows. Create an independent Sub procedure that clears the three payment amounts. Call the Sub procedure when a change is made to the contents of either text box. Also call the Sub procedure whenever the check box is clicked. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. INTRODUCTORY 4. Open the Grade Solution (Grade Solution.sln) file contained in the ClearlyVB2010\ Chap16\Grade Solution folder. The application should display a letter grade, which is based on the average of three test scores. If the average is at least 90, the grade is A. If the average is at least 80 but less than 90, the grade is B. If the average is at least 70 but less than 80, the grade is C. If the average is at least 60 but less than 70, the grade is D. If the average is below 60, the grade is F. Code the application, using an independent Sub procedure to both determine and display the letter grade. Save the298 CHAPTER 16 I Hear You Are Breaking Up (Sub Procedures) solution and then start and test the application. Close the Code Editor window and then close the solution. 5. In this exercise, you modify the Grade application from Exercise 4. Use Windows to INTRODUCTORY make a copy of the Grade Solution folder. Save the copy in the ClearlyVB2010\Chap16 folder. Rename the copy Modified Grade Solution. Open the Grade Solution (Grade Solution.sln) file contained in the Modified Grade Solution folder. Open the designer and Code Editor windows. Currently, the independent Sub procedure both determines and displays the letter grade. Modify the code so that the Sub procedure determines but does not display the letter grade. The letter grade should be displayed by the btnDisplay control’sClickevent procedure. (Hint: If theCodeEditorindicates that aString variable isbeingpassedbeforeithasbeenassignedavalue,assigntheString.Emptyconstantto the variable in the Dim statement.) Save the solution and then start and test the application. Close the Code Editor window and then close the solution. INTERMEDIATE 6. Open theTemperatureSolution(TemperatureSolution.sln)file contained inthe ClearlyVB2010\Chap16\TemperatureSolutionfolder.Codetheapplicationsothatituses twoindependentSubprocedures:onetoconvertatemperaturefromFahrenheittoCelsius, andtheothertoconvertatemperaturefromCelsiustoFahrenheit.Savethesolutionand thenstartandtesttheapplication.ClosetheCodeEditorwindowandthenclosethesolution. INTERMEDIATE 7. Open the Translator Solution (Translator Solution.sln) file contained in the ClearlyVB2010\Chap16\Translator Solution folder. Code the application so that it uses independent Sub procedures to translate the English words into French, Spanish, or Italian. (Hint: If the Code Editor indicates that a String variable is being passed before it has been assigned a value, assign the String.Empty constant to the variable in the Dim statement.) Save the solution and then start and test the application. Close the Code Editor window and then close the solution. INTERMEDIATE 8. In this exercise, you modify the Happy Birthday application coded in the chapter. Use Windows to make a copy of the Birthday Solution folder. Save the copy in the ClearlyVB2010\Chap16 folder. Rename the copy Birthday Solution-Intermediate. Open the Birthday Solution (Birthday Solution.sln) file contained in the Birthday Solution- Intermediate folder. Open the designer window. The ShowMsg procedure should use another independent Sub procedure to assign the appropriate letters (“st”, “nd”, “rd”,or “th”).CreatetheSubprocedureandthenmodifytheShowMsgprocedureappropriately. NoticethatanindependentSubprocedurecancallanotherindependentSubprocedure. (Hint: If the Code Editor indicates that a String variable is being passed before it has been assigned a value, assign the String.Empty constant to the variable in the Dim statement.) Save the solution and then start and test the application. Close the Code Editor window and then close the solution. INTERMEDIATE 9. In this exercise, you code an application that calculates a water bill. The clerk at the water department will enter the current meter reading and the previous meter reading in two text boxes. The application should calculate and display the number of gallons of water used and the total charge for the water. The charge for water is 2.05 per 1000 gallons, or .00205 per gallon. Use two independent Sub procedures: one to make the calculations and the other to display the results. Call both Sub procedures from the Calculate button’s Click event procedure. Make the calculations only when the current meter reading is greater than or equal to the previous meter reading; otherwise, display an appropriate message in a message box. a. List the output and input items, as well as any processing items, and then create an appropriate algorithm using pseudocode. b. CreateaVisualBasicWindowsapplication.Usethefollowingnamesforthesolution and project, respectively: Water Bill Solution and Water Bill Project. Save the application in the ClearlyVB2010\Chap16 folder. Change the name of the form file on your disk to frmMain.vb. If necessary, change the form’s name to frmMain.

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.