Two-Dimensional Arrays

Two-Dimensional Arrays
Dr.NaveenBansal Profile Pic
Dr.NaveenBansal,India,Teacher
Published Date:25-10-2017
Your Website URL(Optional)
Comment
CHAPTER18 A Ray of Sunshine (One-Dimensional Arrays) After studying Chapter 18, you should be able to: Explain the purpose of an array Create a one-dimensional array Store data in a one-dimensional array Sort the contents of a one-dimensional array Search a one-dimensional array320 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) Let’s Join the Group All of the applications you have coded since Chapter 6 have used simple variables. A simple variable, also called a scalar variable, is one that is unrelated to any other variable in memory. At times, however, you will encounter situations where some of the variables in an application are related to each other. In those cases, it is easier and more efficient to treat the related variablesas agroup. Youalready arefamiliarwiththe concept ofgrouping.Thecutlery inone of your kitchen drawers is typically separated into groups, such as forks, knives, and spoons. You also probably have your CD (compact disc) collection grouped either by music type or artist. If yourcollectionisgroupedbyartist,itwilltakeonlyafewsecondstofindallyourFrankSinatraCDs and,dependingonthenumberofFrankSinatraCDsyouown,onlyashorttimeafterthattolocatea particular CD. When you group together related variables, the group is referred to as an array of variablesor,moresimply,anarray.Youmightuseanarrayof12Stringvariablestostorethenames of the 12 months in a year. Or, you might use an array of 50 Decimal variables to store the sales amountsmadeineachofthe50states.Themostcommonlyusedarraysinbusinessapplicationsare one-dimensionalandtwo-dimensional.Youwilllearnaboutone-dimensionalarraysinthischapter and also in the next chapter. Two dimensional arrays are covered in Chapter 20. Each variable in an array has the same name and data type. You distinguish one variable in a one-dimensional array from another variable in the array using a unique number, called a subscript. The subscript indicates the variable’s position in the array and is assigned by the computer when the array is created in internal memory. The first variable in a one-dimensional array is assigned a subscript of 0, the second a subscript of 1, and so on. You refer to each variable in an array by the array’s name and the variable’s subscript, which is specified in a set of parentheses immediately following the array name. To refer to the first variable in a one- dimensional String array named strFriends, you use strFriends(0)—read “strFriends sub zero.” Similarly, to refer to the third variable in the strFriends array, you use strFriends(2). Figure 18-1 shows this naming convention using the storage bin illustration from Chapter 6. The intAge, decRate, and strMonth variables included in the figure are scalar variables. int Age strFriends(0) Sue 21 strFriends(1) Bob strFriends(2) John d ecRate .1 strFriends(3) Mary July strMonth Figure 18-1 Illustration of the naming convention for the one-dimensional strFriends array321 Let’s Join the Group Figure 18-2 shows two versions of the syntax for declaring a procedure-level one-dimensional array in Visual Basic. The figure also includes examples of using both versions. In each syntax, arrayNameisthe nameofthearrayanddataTypeisthetypeof datathearrayvariables,referred to as elements, will store. In Version 1 of the syntax, highestSubscript is an integer that specifies the highest subscript in the array. When the array is created, it will contain one element more than the number specified in the highestSubscript argument; this is because the first element in a one-dimensional array has a subscript of 0. As a result, the intNumbers array declared in Example 1 will contain six elements with subscripts of 0, 1, 2, 3, 4, and 5. When you use Version 1 of the syntax, the computer automatically initializes each element in the array when the array is created. The elements in a numeric array are initialized to the number 0. The elements in a String array, on the other hand, are initialized using the keyword Nothing. The elements do not actually contain the word “Nothing”; rather, they contain no data at all. Ratherthanhavingthe computeruseadefaultvalue toinitializeeacharrayelement,youcan use Version 2 of the syntax to specify each element’s initial value when the array is declared. Assigning initial valuesto anarray isoften referred toaspopulatingthearray.You list the initial values in the initialValues section of the syntax, using commas to separate the values, and you enclose the list of values in braces (). Notice that Version 2’s syntax does not include the highestSubscript argument; instead, an empty set of parentheses follows the array name. The computer automatically calculates the highest subscript based on the number of values listed in the initialValues section. Because the first subscript in a one-dimensional array is the number 0, the highest subscript is always one number less than the number of values listed in the initialValues section. The Dim strFriends() As String = "Sue", "Bob", "John", "Mary" statement in Example 2 in Figure 18-2, for instance, creates a four-element array with subscripts of 0, 1, 2, and 3. The computer assigns the string“Sue” to the strFriends(0) element,“Bob” to the strFriends(1) element, “John” to the strFriends(2) element, and “Mary” to the strFriends(3) element, as shown earlier in Figure 18-1. Declaring a procedure-level one-dimensional array Syntax—Version 1 Dim arrayName(highestSubscript) As dataType Syntax—Version 2 Dim arrayName() As dataType = initialValues Example 1—Version 1’s syntax Dim intNumbers(5) As Integer declares and initializes (to 0) a six-element Integer array named intNumbers Example 2—Version 2’s syntax Dim strFriends() As String = "Sue", "Bob", "John", "Mary" declares and initializes a four-element String array named strFriends Figure 18-2 Syntax versions and examples of declaring a procedure-level one-dimensional array The variables (elements) in an array can be used just like any other variables: You can assign values to them, use them in calculations, display their contents, and so on. Figure 18-3 shows examples of statements that perform these tasks.322 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) Using an element in a one-dimensional array Example 1 Dim strCities() As String = "Paris", "Rome", "Lisbon" strCities(0) = "Madrid" assigns the string “Madrid” to the first element in the strCities array, replacing the string “Paris” Example 2 Dim intSalaries() As Integer = 25000, 35000, 50000, 23000 intSalaries(3) = intSalaries(3) + 2000 adds 2000 to the contents of the last element in the intSalaries array (23000) and then assigns the result (25000) to the element Example 3 Dim decSales(10) As Decimal Decimal.TryParse(txtSales.Text, decSales(2)) lblSales.Text = decSales(2).ToString("C2") assigns the value returned by the TryParse method to the third element in the decSales array and then displays the value (formatted with a dollar sign and two decimal places) in the lblSales control Figure 18-3 Examples of using an element in a one-dimensional array The procedures you code in this chapter will demonstrate some of the ways one-dimensional arraysareused in an application. Inmostapplications, the valuesstored in anarraycome from a fileonthe computer’sdiskandareassignedtothearrayafteritisdeclared.However,sothatyou can follow the code and its results more easily, the applications in this chapter use the Dim statement to store the appropriate values in the array. Mini-Quiz 18-1 See Appendix B for the answers. 1. Write a Visual Basic statement that declares a 20-element one-dimensional Integer array named intQuantities. 2. What is the highest subscript in the intQuantities array from Question 1? 3. Write a Visual Basic statement that assigns the number 7 to the fourth element in the intQuantities array. My Friends Application The My Friends application will store four names in a one-dimensional String array named strFriends. It then will display the contents of the array in three label controls named lblOriginal, lblAscending, and lblDescending. In the lblOriginal control, the names will appear in the same order as in the array. In the lblAscending and lblDescending controls, the names will appear in ascending and descending order, respectively.323 My Friends Application To begin coding the My Friends application: 1. Start Visual Studio 2010 or Visual Basic 2010 Express and permanently display the Solution Explorer window. Open the Friends Solution (Friends Solution.sln) file contained in the ClearlyVB2010\Chap18\Friends Solution folder. If the designer window is not open, double-click frmMain.vb in the Solution Explorer window. 2. Open the Code Editor window and then open the code template for the btnDisplay control’s Click event procedure. Type the following comments and then press Enter twice: ' displays names in original, ascending, ' and descending order 3. First, you will declare and initialize the strFriends array. Type the following declaration statement and then press Enter twice: Dim strFriends() As String = "Sue", "Bob", "John", "Mary" 4. Now you will clear the contents of the three label controls. Type the following comment and three assignment statements. Press Enter twice after typing the last assignment statement. ' clear label controls lblOriginal.Text = String.Empty lblAscending.Text = String.Empty lblDescending.Text = String.Empty Next, you will display the contents of the array in the lblOriginal control. You can accomplish this task using a loop to access each element in the array, beginning with the element whose subscript is 0 and ending with the element whose subscript is 3. Because you want the loop instructions processed a precise number of times—in this case, from 0to3—you will code the loop using the For…Next statement. As you learned in Chapter 14, the For…Next statement provides a more convenient way to code a counter- controlled loop, because it takes care of initializing and updating the counter variable, as well as evaluating the loop condition. Figure 18-4 shows two versions of the code for displaying the contents of the strFriends array in the lblOriginal control. Only the endValue in the For clause is different in each version. In Version 1, the endValue is 3 (the highest subscript in the array). In Version 2, the endValue is the expressionstrFriends.Length–1.Theexpressionusesthearray’sLengthproperty,which contains an integer that represents the number of elements in the array; in this case, the Length property contains the number 4. To determine the highest subscript in the array, you simply subtract the number 1 from the value stored in the array’s Length property, as shown in the expression. Although both versions of code in Figure 18-4 will work, Version 2’s code is the preferred one for several reasons. First, if you use the Length property, you won’t have to count the number of array elements yourself. Second, the Length property is essential when you don’t know the exact number of array elements; this may be the case when the array values come from a file. Finally, if the number of array elements changes in the future, the Length property’s value will automatically adjust.324 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) endValue Version 1 For intSub As Integer = 0 To 3 lblOriginal.Text = lblOriginal.Text & strFriends(intSub) & ControlChars.NewLine Next intSub endValue Version 2 For intSub As Integer = 0 To strFriends.Length - 1 lblOriginal.Text = lblOriginal.Text & strFriends(intSub) & ControlChars.NewLine Next intSub Figure 18-4 Two versions of the code for displaying the array’s contents To continue coding the btnDisplay control’s Click event procedure: 1. Enter the following comment and four lines of code: ' display array in original order For intSub As Integer = 0 To strFriends.Length – 1 lblOriginal.Text = lblOriginal.Text & strFriends(intSub) & ControlChars.NewLine Next intSub 2. Save the solution and then start the application. Click the Display button. The names Sue, Bob, John, and Mary appear in the lblOriginal control, as shown in Figure 18-5. Click the Exit button. Figure 18-5 Array contents displayed in the Original order box Before displaying the array values in the lblAscending and lblDescending controls, you need to arrange the values in the appropriate order. Arranging data in a specific order is called sorting. Visual Basic provides theArray.Sortmethod for sorting the values in a one-dimensional array in ascending order. When an array is sorted in ascending order, the first element in the array contains the smallest value and the last element contains the largest value. To sort the array values in descending order, you first use the Array.Sort method to sort the values in ascending order and then use the Array.Reversemethod to reverse the order of the values. When an array issortedindescendingorder,thefirstelementinthearraycontainsthelargestvalueandthelast element contains the smallest value. Figure 18-6 shows the syntax of both methods and includes examples of using the methods.325 My Friends Application Array.Sort and Array.Reverse methods Syntax Array.Sort(arrayName) Array.Reverse(arrayName) Example 1 Dim intNums() As Integer = 1, 3, 10, 2, 4, 23 Array.Sort(intNums) sorts the values in the intNums array in ascending order as follows: 1, 2, 3, 4, 10, 23 Example 2 Dim intNums() As Integer = 1, 3, 10, 2, 4, 23 Array.Reverse(intNums) reverses the order of the values in the intNums array as follows: 23, 4, 2, 10, 3, 1 Example 3 Dim intNums() As Integer = 1, 3, 10, 2, 4, 23 Array.Sort(intNums) Array.Reverse(intNums) sorts the values in the intNums array in descending order as follows: 23, 10, 4, 3, 2, 1 Figure 18-6 Syntax and examples of the Array.Sort and Array.Reverse methods To complete the btnDisplay control’s Click event procedure: 1. Insert two blank lines below the Next intSub clause. Enter the following comment and five lines of code: ' display array in ascending order Array.Sort(strFriends) For intSub As Integer = 0 To strFriends.Length – 1 lblAscending.Text = lblAscending.Text & strFriends(intSub) & ControlChars.NewLine Next intSub 2. Insert two blank lines below the Next intSub clause from the previous step. Enter the following comment and six lines of code: ' display array in descending order Array.Sort(strFriends) Array.Reverse(strFriends) For intSub As Integer = 0 To strFriends.Length – 1 lblDescending.Text = lblDescending.Text & strFriends(intSub) & ControlChars.NewLine Next intSub Figure 18-7 shows the code entered in the btnDisplay control’s Click event procedure.326 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) Private Sub btnDisplay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDisplay.Click ' displays names in original, ascending, ' and descending order Dim strFriends() As String = "Sue", "Bob", "John", "Mary" ' clear label controls lblOriginal.Text = String.Empty lblAscending.Text = String.Empty lblDescending.Text = String.Empty ' display array in original order For intSub As Integer = 0 To strFriends.Length - 1 lblOriginal.Text = lblOriginal.Text & strFriends(intSub) & ControlChars.NewLine Next intSub ' display array in ascending order Array.Sort(strFriends) For intSub As Integer = 0 To strFriends.Length - 1 lblAscending.Text = lblAscending.Text & strFriends(intSub) & ControlChars.NewLine Next intSub ' display array in descending order Array.Sort(strFriends) Array.Reverse(strFriends) For intSub As Integer = 0 To strFriends.Length - 1 lblDescending.Text = lblDescending.Text & strFriends(intSub) & ControlChars.NewLine Next intSub End Sub Figure 18-7 btnDisplay control’s Click event procedure To test the btnDisplay control’s Click event procedure: 1. Savethesolutionandthenstarttheapplication.ClicktheDisplaybutton.SeeFigure18-8. The Array. Sort method is not the only way to sort the contents of an array. To learn more about Figure 18-8 Array values displayed in the three label controls sorting arrays, see the Sorting Routines section in 2. Click the Exit button. Close the Code Editor window and then close the solution. theCh18WantMore.pdffile.327 Salary Application Salary Application The Salary application will store six salary amounts in a one-dimensional Integer array named intSalaries.Eachsalaryamountcorrespondstoasalarycode;thevalidcodesarethenumbers 1 through 6. Code 1’s salary is stored in the intSalaries(0) element in the array, code 2’s salary in the intSalaries(1) element, and so on. Notice that the code is one number more than the subscript of its corresponding salary in the array. After storing the salary amounts in the array, the application will prompt the user to enter a salary code. It then will display the amount associated with the code. Figure 18-9 shows the planning information for the application. Output: salary amount Processing: six element one dimensional array of salary amounts array subscript Input: salary code (1 through 6) Algorithm: 1. enter the salary code 2. calculate the subscript of the array element associated with the salary code by subtracting 1 from the salary code 3. use the array subscript to display (in a label control) the associated salary amount from the array Figure 18-9 Planning information for the Salary application To code and then test the Salary application: 1. Open the Salary Solution (Salary Solution.sln) file contained in the ClearlyVB2010\ Chap18\Salary Solution folder. If the designer window is not open, double-click frmMain.vb in the Solution Explorer window. 2. Open the Code Editor window and then open the code template for the btnDisplay control’s Click event procedure. Type the following comment and then press Enter twice: ' displays the salary amount associated with a code 3. First, you will declare and initialize the intSalaries array. Enter the following array declaration statement: Dim intSalaries() As Integer = 25000, 35000, 55000, 70000, 80200, 90500 4. Now you will declare the necessary variables. Enter the following declaration statements. Press Enter twice after typing the last declaration statement. Dim intCode As Integer Dim intSub As Integer 5. The first step in the algorithm is to enter the salary code. The user enters the code in the txtCode control. You will use the TryParse method to convert the code to the Integer data type, storing the result in the intCode variable. Enter the following TryParse method: Integer.TryParse(txtCode.Text, intCode)328 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) 6. Step 2 in the algorithm is to calculate the subscript of the array element associated with the salary code. You do this by subtracting the number 1 from the salary code. Enter the following comment and assignment statement. Press Enter twice after typing the assignment statement. ' calculate the appropriate subscript intSub = intCode – 1 7. The last step in the algorithm is to use the array subscript to display the appropriate salary amount from the array. Enter the following comment and assignment statement: ' display the salary amount from the array lblSalary.Text = intSalaries(intSub) 8. Save the solution and then start the application. Type 2 in the Code box and then click the Display Salary button. The salary amount stored in the intSalaries(1) element appears in the Salary box, as shown in Figure 18-10. Figure 18-10 Interface showing the salary for code 2 9. Now you will observe the result of entering an invalid salary code. Replace the 2 in the Codeboxwith8andthenclicktheDisplaySalarybutton.Aruntimeerroroccurs.Asa result, the Code Editor highlights the lblSalary.Text = intSalaries(intSub) statement, which is the statement where the error was encountered; it also opens a help box. The help box indicates that the index (which is another term for subscript) is outside the bounds of the array. 10. PlaceyourmousepointeronintSubinthehighlightedstatement,asshowninFigure18-11. The variable contains the number 7, which is one number less than the salary code you entered. The valid subscripts for the array, however, are the numbers 0 through 5 only. the number 7 is an help box invalid array subscript Figure 18-11 Result of the run time error caused by an invalid array subscript 11. Click Debug on the menu bar and then click Stop Debugging.329 Salary Application Before it attempts to access an array element, a procedure should verify that the subscript being used is valid. This can be accomplished using a selection structure whose condition verifies that the subscript is within an acceptable range for the array. The acceptable range is a number that is greater than or equal to 0 but less than the number of array elements. If the subscript is not in the acceptable range, the procedure should not try to access the element because doing so results in a run time error. Figure 18-12 shows the modified algorithm for the Salary application. Notice that Step 3 now validates the array subscript. Output: salary amount Processing: six element one dimensional array of salary amounts array subscript Input: salary code (1 through 6) Algorithm: 1. enter the salary code 2. calculate the subscript of the array element associated with the salary code by subtracting 1 from the salary code 3. if the array subscript is greater than or equal to 0 but less than the number of array elements, do this: use the array subscript to display (in a label control) the associated salary amount from the array otherwise, do this: clear the salary amount from the label control display a message informing the user that the salary code is invalid end if Figure 18-12 Modified algorithm for the Salary application To modify and then test the btnDisplay control’s Click event procedure: 1. Enter the selection structure shown in Figure 18-13. (You will need to move the last comment and assignment statement, which you entered in Step 7 in the previous set of steps, into the selection structure’s true path.)330 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) Private Sub btnDisplay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDisplay.Click ' displays the salary amount associated with a code Dim intSalaries() As Integer = 25000, 35000, 55000, 70000, 80200, 90500 Dim intCode As Integer Dim intSub As Integer Integer.TryParse(txtCode.Text, intCode) ' calculate the appropriate subscript intSub = intCode - 1 If intSub = 0 AndAlso intSub intSalaries.Length Then ' display the salary amount from the array lblSalary.Text = intSalaries(intSub) Else enter this selection lblSalary.Text = String.Empty structure MessageBox.Show("Valid salary codes are 1 through 6", "Salary", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub Figure 18-13 Modified btnDisplay control’s Click event procedure 2. Save the solution and then start the application. Type 3 in the Code box and then click the Display Salary button. The number 55000 appears in the Salary box. 3. Replace the 3 in the Code box with 9 and then click the Display Salary button. The message “Valid salary codes are 1 through 6” appears in a message box. Close the message box. Notice that the Salary box is now empty. 4. On your own, test the application using salary codes of 2 through 6. Also test it by clicking the Display Salary button without entering any data. 5. When you are finished testing the application, click the Exit button. Close the Code Editor window and then close the solution. States Application The States application stores the names of nine states in a one-dimensional String array named strStates. The names are stored in the order each was visited by the user. For example, the user visited Hawaii first, followed by Colorado. Therefore, the strings “Hawaii” and “Colorado” are stored in the strStates(0) and strStates(1) elements, respectively. The application’s interface provides a text box for the user to enter a state name. The application searches for the state name in the array, beginning with the first array element. It then displays a message indicating whether the state name was found. Sample messages include “Hawaii is number 1 in the list of states you visited” and “You did not visit Illinois”. Figure 18-14 shows the planning information for the application.331 States Application Output: message Processing: nine element one dimensional array of state names array subscript found Input: state name to search for Algorithm: 1. enter the state name to search for, and then convert the state name to uppercase 2. assign 0 to the array subscript 3. assign “N” to found 4. repeat until found “Y” or the array subscript equals the number of array elements: If the contents of the current array element (converted to uppercase) is the same as the state name to search for, do this: assign “Y” to found otherwise, do this: add 1 to the array subscript end if end repeat 5. if found “Y”, do this: display the state name and visited rank in an appropriate message otherwise, do this: display the state name in an appropriate message end if Figure 18-14 Planning information for the States application To code the States application: 1. Open the States Solution (States Solution.sln) file contained in the ClearlyVB2010\ Chap18\States Solution folder. If the designer window is not open, double-click frmMain.vb in the Solution Explorer window. 2. Open the Code Editor window and then locate the code template for the btnVisited control’s Click event procedure. The procedure declares and initializes the strStates array. 3. First,youwilldeclare the necessary variables:strSearchFor,intSub,and strFound.The strSearchFor variable will store the name of the state to search for in the array. The intSub variable will keep track of the array subscripts during the search. The strFound variable will keep track of whether the state name was found in the array. Click the blank line above the EndSub clause and then press Enter. Enter the following three declaration statements. Press Enter twice after typing the last declaration statement. Dim strSearchFor As String Dim intSub As Integer Dim strFound As String 4. Now you will convert the contents of the txtState control to uppercase and then assign the result to the strSearchFor variable. After doing this, the variable will contain the name of the state to search for in the array. Enter the following assignment statement: strSearchFor = txtState.Text.ToUpper332 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) 5. As mentioned earlier, the search should begin with the first array element. Enter the following assignment statement: intSub = 0 6. Before the search begins, the procedure will assume that the state is not contained in the array. Enter the following assignment statement: strFound = "N" 7. Step 4 in the algorithm is a loop that repeats its instructions until one of two conditions is true: either the state name has been found in the array or the subscript equals the number of array elements (which indicates there are no more elements to search). You will use the Do…Loop statement to code this loop. The For…Next statement is not appropriate in this case, because you don’t know the exact number of times the loop instructions should be repeated. Enter the following Do clause: Do Until strFound = "Y" OrElse intSub = strStates.Length 8. Thefirstinstructionintheloopisaselectionstructurethatcomparesthecontentsofthe current array element (converted to uppercase) with the state name stored in the strSearchFor variable. If both names match, the selection structure’s true path will assign the string “Y” to the strFound variable to indicate that the name was located in the array. If both names do not match, the selection structure’s false path will increment the array subscript by 1; this will allow the loop to search the next element in the array. Enter the following selection structure: If strStates(intSub).ToUpper = strSearchFor Then strFound = "Y" Else intSub = intSub + 1 End If 9. The value stored in the strFound variable indicates whether the state name was located in the array, and it determines the appropriate message to display. Insert two blank lines below the Loop clause and then enter the following selection structure: If strFound = "Y" Then lblMessage.Text = strSearchFor & " is number " & intSub + 1 & " in the list of states you visited" Else lblMessage.Text = "You did not visit " & strSearchFor End If Figure 18-15 shows the code entered in the btnVisited control’s Click event procedure.333 States Application Private Sub btnVisited_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnVisited.Click ' searches an array for the name of a state, and ' then displays an appropriate message Dim strStates() As String = "Hawaii", "Colorado", "Florida", "California", "Georgia", "Idaho", "North Carolina", "Texas", "New York" Dim strSearchFor As String Dim intSub As Integer Dim strFound As String strSearchFor = txtState.Text.ToUpper intSub = 0 strFound = "N" Do Until strFound = "Y" OrElse intSub = strStates.Length If strStates(intSub).ToUpper = strSearchFor Then strFound = "Y" Else you also can use intSub += 1 intSub = intSub + 1 End If Loop If strFound = "Y" Then lblMessage.Text = strSearchFor & " is number " & intSub + 1 & " in the list of states you visited" Else lblMessage.Text = "You did not visit " & strSearchFor End If End Sub Figure 18-15 btnVisited control’s Click event procedure To test the btnVisited control’s Click event procedure: 1. Save the solution and then start the application. First, you will enter a state name that is contained in the array. Type Texas in the State box and then click the Visited? button. The appropriate message appears in the interface. See Figure 18-16. Figure 18-16 Interface showing the message for Texas 2. Now you will enter a state name that is not in the array. Replace Texas in the State box withLouisiana andthen click theVisited? button.The“You didnot visitLOUISIANA” message appears in the interface.334 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) 3. On your own, test the application using different state names. When you are finished testing the application, click the Exit button. Close the Code Editor window and then close the solution. Mini-Quiz 18-2 To review what you See Appendix B for the answers. learned 1. Write a Visual Basic statement that sorts the strStates array in ascending order. about one- dimensional 2. The number of array elements is stored in an array’s property. arrays, view the 3. If the dblBonus array contains 10 elements, what will happen when the computer Ch18One-Dimensional processes the dblBonus(10) = 35.67 statement? Arrays video. Summary l All of the variables in an array have the same name and data type. l Each element in a one-dimensional array is identified by a unique integer, called a subscript. The subscript appears in parentheses after the array’s name. The first subscript in a one- dimensional array is 0. l When declaring a one-dimensional array, you provide either the highest subscript or the initial values. l The number of elements in a one-dimensional array is one number more than its highest subscript. l You refer to an element in a one-dimensional array using the array’s name followed by the element’s subscript. l You can use an array variable just like any other variable. l A one-dimensional array’s Length property contains an integer that represents the number of elements in the array. l The Array.Sort method sorts the elements in a one-dimensional array in ascending order. The Array.Reverse method reverses the order of the elements in a one-dimensional array. Key Terms Array—a group of related variables that have the same name and data type Array.Reverse method—reverses the order of the values stored in a one-dimensional array Array.Sort method—sorts the values stored in a one-dimensional array in ascending order Elements—the variables in an array Length property—one of the properties of a one-dimensional array; stores an integer that represents the number of array elements Populating the array—refers to the process of initializing the elements in an array Scalar variable—another name for a simple variable Simple variable—a variable that is unrelated to any other variable in the computer’s internal memory; also called a scalar variable335 Review Questions Sorting—the process of arranging data in a specific order Subscript—a unique integer that identifies the position of an element in an array Review Questions 1. Which of the following declares a four-element one-dimensional array named strLetters? a. Dim strLetters(3) As String c. Dim strLetters(3) As String = "A", "B", "C", "D" b. Dim strLetters() As String = d. both a and c "A", "B", "C", "D" 2. Which of the following assigns (to the lblCount control) the number of elements contained in the intItems array? a. lblCount.Text = intItems.Len b. lblCount.Text = intItems.Length c. lblCount.Text = Length(intItems) d. lblCount.Text = intItems.NumElements 3. TheintItems arrayisdeclared usingtheDimintItems(20)AsInteger statement.The intSub variable keeps track of the array subscripts and is initialized to 0. Which of the following Do clauses tells the computer to process the loop instructions for each element in the array? a. Do While intSub 20 c. Do While intSub = 20 b. Do While intSub 20 d. Do While intSub = 20 4. The decSales array is declared using the Dim decSales(4) As Decimal statement. Which of the following If clauses can be used to validate the array subscript stored in the intX variable? a. If decSales(intX) = 0 AndAlso c. IfintX=0AndAlsointX4Then decSales(intX) 4 Then b. IfdecSales(intX)=0AndAlso d. none of the above decSales(intX) = 4 Then 5. The decSales array is declared using the Dim decSales(4) As Decimal statement. Which of the following loops will correctly add 100 to each element in the array? a. intX = 0 Do While intX = 4 decSales(intX) = decSales(intX) + 100 intX = intX + 1 Loop b. For intSubscript As Integer = 0 To 4 decSales(intSubscript) += 100 Next intSubscript c. intX = 0 Do decSales(intX) = decSales(intX) + 100 intX = intX + 1 Loop Until intX 4 d. all of the above336 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) 6. The strCities array is declared using the Dim strCities(10) As String statement. The intSub variable keeps track of the array subscripts and is initialized to 0. Which of the following Do clauses tells the computer to process the loop instructions for each element in the array? a. Do While intSub strCities.Length b. Do While intSub = strCities.Length – 1 c. Do Until intSub = strCities.Length d. all of the above 7. The strLetters array is declared using the DimstrLetters()AsString="E","A", "C", "G" statement. Which of the following will sort the array as follows: G, E, C, A? a. Array.Sort(strLetters) Array.Reverse(strLetters) b. Array.Reverse(strLetters) Array.Sort(strLetters) c. Array.SortDescending(strLetters) d. both a and b Exercises 1. Open the Party List Solution (Party List Solution.sln) file contained in the TRY THIS ClearlyVB2010\Chap18\Party List Solution folder. The interface provides a text box for the userto enter a name.When the userclicks the VerifyInvitation button, the button’s Click event procedure should display (in a message box) either the message “NAME is invited.” or “NAME is not invited.” In each message, NAME is the name entered by the user. Open the code template for the btnVerify control’s Click event procedure. Declare an array containing the following names: Jacob, Karen, Gregory, Jerome, Susan, Michele, Heather, Jennifer, and George. Code the procedure using the While keyword in the Do clause. 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.) 2. Open the Grades Solution (Grades Solution.sln) file contained in the ClearlyVB2010\ TRY THIS Chap18\Grades Solution folder. The interface provides a text box for the user to enter a letter grade. When the user clicks the Count button, the button’s Click event procedure should display (in a message box) the message “Grade: number”, where Grade is the letter grade entered by the user, and number is the number of times the student earned the grade. Open the code template for the btnCount control’s Click event procedure. Declare an array containing the following letter grades: A, B, C, A, B, A, F, A, D, B, and C. Code the procedure using the For…Next statement. Save the solution and then start andtesttheapplication.Closethe CodeEditorwindowandthenclosethesolution.(See Appendix B for the answer.) 3. Inthisexercise,youmodifytheapplicationcodedinExercise2.UseWindowstomakea MODIFY THIS copy of the Grades Solution folder. Save the copy in the ClearlyVB2010\Chap18 folder. Rename the copy Grades Solution-MODIFY THIS. Open the Grades Solution (Grades Solution.sln) file contained in the Grades Solution-MODIFY THIS folder. Open the designer window. Change the For…Next statement in the Count button’s Click event procedure to a Do…Loop statement. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. 4. Open the Bonus Solution (Bonus Solution.sln) file contained in the Bonus Solution INTRODUCTORY folder. Open the Code Editor window. The btnDisplay control’s Click event procedure should display the total of the values stored in the dblBonus array, formatted with a337 Exercises dollarsignandtwodecimalplaces.Codethe procedure.Savethesolutionandthenstart and test the application. Close the Code Editor window and then close the solution. 5. Open the NumDays Solution (NumDays Solution.sln) file contained in the INTRODUCTORY ClearlyVB2010\Chap18\NumDays Solution folder. Open the code template for the btnDisplay control’s Click event procedure. Declare a 12-element one-dimensional array. Use the number of days in each month to initialize the array. (Use 28 for February.) The procedure should display (in the lblDays control) the number of days corresponding tothemonth numberenteredbythe user.Forexample,iftheuserenters the number 1, the procedure should display 31 in the lblDays control, because there are 31 days in January. The procedure should display an appropriate message in a message box when the user enters an invalid month number. Code the procedure. Save the solution and then start and test the application. Closethe Code Editorwindow andthen close the solution. 6. Open the Update Prices (Update Prices Solution.sln) file contained in the INTRODUCTORY ClearlyVB2010\Chap18\Update Prices Solution folder. The btnUpdate control’s Click event procedure should display (in the lblOriginal control) each price stored in the dblPrices array. It then should increase each price by 2 and then display the updated array values in the lblIncreased control. Display the original and updated prices with two decimal places. Code the procedure. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. 7. Open the Scores Solution (Scores Solution.sln) file contained in the ClearlyVB2010\ INTRODUCTORY Chap18\Scores Solution folder. Open the code template for the btnDisplay control’s Click event procedure. Declare a 20-element one-dimensional array, using the following numbers to initialize the array: 88, 72, 99, 20, 66, 95, 99, 100, 72, 88, 78, 45, 57, 89, 85, 78, 75, 88, 72, and 88. The procedure should prompt the user to enter a score from 0 through 100. It then should display (in a message box) the number of students who earned that score. Save the solution and then start the application. How many students earned a score of 72? How many earned a score of 88? How many earned a score of 20? How many earned a score of 99? Close the Code Editor window and then close the solution. 8. Inthisexercise,youmodifytheapplicationfromExercise7.UseWindowstomakeacopy INTERMEDIATE of theScoresSolution folder.Savethecopy in theClearlyVB2010\Chap18folder. Rename the copy Scores Solution-Range. Open the Scores Solution (Scores Solution.sln) file contained in the Scores Solution-Range folder. Open the designer and Code Editor windows. The btnDisplay control’s Click event procedure should prompt the user to enter a minimum score and a maximum score. It then should display (in a message box) the number of students who earned a score in that range. Save the solution and then start the application. How many students earned a score from 70 through 79, inclusive? How many earned a score from 65 through 85, inclusive? How many earned a score from 0 through 50, inclusive? Close the Code Editor window and then close the solution. 9. In this exercise, you modify the application you coded in Exercise 7. Use Windows to INTERMEDIATE make a copy of the Scores Solution folder. Save the copy in the ClearlyVB2010\Chap18 folder. Rename the copy Scores Solution-Average. Open the Scores Solution (Scores Solution.sln) file contained in the Scores Solution-Average folder. Open the designer and Code Editor windows. Remove the existing code from the btnDisplay control’s Click event procedure; however, leave the array declaration statement. Code the procedure so that it displays (in a message box) the average score in the array. Save the solution and then start and test the application. Closethe Code Editorwindow andthen close the solution. 10. JM Sales employs eight salespeople. The sales manager wants an application that allows ADVANCED him toenter abonusrate.Theapplication shoulduse the rate,alongwiththeeight sales338 CHAPTER 18 A Ray of Sunshine (OneDimensional Arrays) amounts stored in an array, to calculate each salesperson’s bonus amount. It also should calculate the total bonus paid to the salespeople. The application should display each salesperson’s number (1 through 8) and bonus amount, as well as the total bonus paid, in the interface. Figure 18-17 shows a sample run of the application. a. List the output and input items, as well as any processing items, and then create an appropriate algorithm using pseudocode. b. CreateaVisualBasicWindowsapplication. Usethe followingnamesforthe solution and project, respectively: JM Sales Solution and JM Sales Project. Save the application in the ClearlyVB2010\Chap18 folder. Change the name of the form file on your disk to frmMain.vb. If necessary, change the form’s name to frmMain. c. Create the interface shown in Figure 18-17. The txtReport control uses the Courier New font. The control’s Multiline and ReadOnly properties are set to True, and its ScrollBars property is set to Vertical. d. Code the application. The txtRate control should accept only numbers, the period, and the Backspace key. The contents of the txtReport control should be cleared when a change is made to the contents of the txtRate control. Use a one- dimensional array whose elements are initialized to the following sales amounts: 2400, 1500, 1600, 2790, 1000, 6300, 1300, and 2700. e. Save the solution and then start the application. Enter .1 as the bonus rate and then clickthe Create Report button.Theinterfaceshould appear asshownin Figure 18-17. Alsotesttheapplicationusingyourowndata.ClosetheCodeEditorwindowandthen close the solution. txtRate txtReport Figure 18-17 Sample run of the JM Sales application 11. In this exercise, you create an application that displays the highest and lowest values ADVANCED stored in an array. a. Open the HighLow Solution (HighLow Solution.sln) file contained in the ClearlyVB2010\Chap18\HighLow Solution folder. Open the Code Editor window. b. Locate the btnHighest control’s Click event procedure. First, the procedure should sort the test scores to determine the highest score stored in the array. It then should count the number of students earning that score. Display the highest score, as well as the number of students earning that score, in the interface. Code the procedure. Save the solution and then start and test the application. Stop the application.

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