Presentation is loading. Please wait.

Presentation is loading. Please wait.

Visual Basic 2010 How to Program

Similar presentations


Presentation on theme: "Visual Basic 2010 How to Program"— Presentation transcript:

1 Visual Basic 2010 How to Program
Arrays Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.

2 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

3 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

4 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

5 7.1  Introduction This chapter introduces basic concepts of data structures—collections of related data items. Arrays are simple data structures consisting only of data items of the same type. Arrays normally are “static” entities, in that they typically remain the same size once they’re created, although they can be resized (as we show in Section 7.16. We discuss arrays that can represent lists and tables of values. © by Pearson Education, Inc. All Rights Reserved.

6 7.1 Introduction We begin by creating and accessing arrays.
We then perform more complex array manipulations, including summing the elements of an array, using arrays to summarize survey results, searching arrays for specific values and sorting arrays so their elements are in ascending order. We also introduce For Each…Next repetition statement and use it to process the elements of an array. © by Pearson Education, Inc. All Rights Reserved.

7 7.2  Arrays An array is a group of variables (called elements) containing values that all have the same type. To refer to a particular element in an array, we specify the name of the array and the position number of the element to which we refer. Figure 7.1 shows a logical representation of an integer array called c. © by Pearson Education, Inc. All Rights Reserved.

8 7.2  Arrays This array contains 12 elements, any one of which can be referred to by giving the name of the array followed by the position number of the element in parentheses (). The first element in every array is the zeroth element. Thus, the names of array c’s elements are c(0), c(1), c(2) and so on. The highest position number in array c is 11 (also called the array’s upper bound), which is 1 less than the number of elements in the array (12). © by Pearson Education, Inc. All Rights Reserved.

9 7.2 Arrays Accessing Array Elements
The position number in parentheses more formally is called an index or “subscript.” An index must be a nonnegative integer or integer expression. If a program uses an expression as an index, the expression is evaluated first to determine the index. For example, if variable value1 is equal to 5, and variable value2 is equal to 6, then the statement c(value1 + value2) += 2 adds 2 to array element c(11). The name of an array element can be used on the left side of an assignment statement to place a new value into an array element. © by Pearson Education, Inc. All Rights Reserved.

10 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

11 7.2 Arrays Let’s examine array c (Fig. 7.1) more closely.
The array’s name is c. Its 12 elements are referred to as c(0) through c(11)—pronounced as “c sub zero” through “c sub 11,” where “sub” derives from “subscript.” The value of c(0) is -45, the value of c(1) is 6, the value of c(7) is 62 and the value of c(11) is 78. © by Pearson Education, Inc. All Rights Reserved.

12 7.2 Arrays Values stored in arrays can be used in calculations.
For example, to determine the total of the values contained in the first three elements of array c and then store the result in variable sum, we would write sum = c(0) + c(1) + c(2) To divide the value of c(6) by 2 using Integer division and assign the result to the variable result, we’d write result = c(6) \ 2 © by Pearson Education, Inc. All Rights Reserved.

13 7.2  Arrays Array Length Every array “knows” its own length (that is, number of elements), which is determined by the array’s Length property, as in: c.Length All arrays have the methods and properties of class System.Array. © by Pearson Education, Inc. All Rights Reserved.

14 7.3 Declaring and Allocating Arrays
The following statement can be used to declare the array in Fig. 7.1: Dim c(11) As Integer The parentheses that follow the variable name indicate that c is an array. Arrays can be declared to contain elements of any type; every element of the array is of that type. For example, every element of an Integer array contains an Integer value. The number in parentheses in the array declaration helps the compiler allocate memory for the array c. © by Pearson Education, Inc. All Rights Reserved.

15 7.3 Declaring and Allocating Arrays
In the preceding declarations, the number 11 defines the array’s upper bound. Array bounds determine what indices can be used to access an element in the array. Here the array bounds are 0 and 11. The bound 0 is implicit in the preceding statement and is always the lower bound of every array. An index outside these bounds cannot be used to access elements in the array c. The actual size of the array is one larger (12) than the specified upper bound. © by Pearson Education, Inc. All Rights Reserved.

16 7.3 Declaring and Allocating Arrays
We also can explicitly specify the array bounds, as in Dim c(0 To 11) As Integer The explicit array bounds specified in the preceding statement indicate that the lower bound of the array is 0 and the upper bound is 11. The size of the array is still 12. Because the lower bound must always be 0, we do not include “0 To” when declaring an array’s bounds in this book. © by Pearson Education, Inc. All Rights Reserved.

17 7.3 Declaring and Allocating Arrays
Initializer Lists You can follow an array declaration with an equal sign and an initializer list in braces ({ and }) to specify the initial values of the array’s elements. For instance, Dim numbers() As Integer = {1, 2, 3, 6} declares and allocates an array containing four Integer values. © by Pearson Education, Inc. All Rights Reserved.

18 7.3 Declaring and Allocating Arrays
The compiler determines the array bounds from the number of elements in the initializer list—you cannot specify the upper bound of the array when an initializer list is present. Visual Basic can also use local type inference to determine the type of an array with an initializer list. So, the preceding declaration can be written as: Dim numbers = {1, 2, 3, 6} © by Pearson Education, Inc. All Rights Reserved.

19 7.3 Declaring and Allocating Arrays
Default Initialization When you do not provide an initializer list, the elements in the array are initialized to the default value for the array’s type—0 for numeric primitive data-type variables, False for Boolean variables and Nothing for String and other class types. © by Pearson Education, Inc. All Rights Reserved.

20 7.4 Initializing the Values in an Array
Figure 7.2 creates two five-element integer arrays and sets their element values, using an initializer list and a For…Next statement that calculates the element values, respectively. The arrays are displayed in tabular format in the outputTextBox. Line 10 combines the declaration and initialization of array1 into one statement. The compiler implicitly allocates the array based on the number of values in the initializer list. Line 13 declares and allocates array2, whose size is determined by the expression array1.GetUpperBound(0). © by Pearson Education, Inc. All Rights Reserved.

21 7.4 Declaring and Allocating Arrays
Array method GetUpperBound returns the index of the last element in the array. The value returned by method GetUpperBound is one less than the value of the array’s Length property. For arrays that represent lists of values, the argument passed to GetUpperBound is 0. In this example, array1.GetUpperBound(0) returns 4, which is then used to specify the upper bound of array2, so array1 and array2 have the same upper bound (4) and the same length (5). This makes it easy to display the arrays’ contents side-by- side. © by Pearson Education, Inc. All Rights Reserved.

22 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

23 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

24 7.4 Initializing the Values in an Array
The For statement in lines 16–18 initializes the elements in array2 to the even integers 2, 4, 6, 8 and 10. These numbers are generated by multiplying each successive value of the loop counter by 2 and adding 2 to the product. The For statement in lines 24–27 displays the values from the two arrays side-by-side in a TextBox. © by Pearson Education, Inc. All Rights Reserved.

25 7.5 Summing the Elements of an Array
Often, the elements of an array represent a series of related values that are used in a calculation. For example, if the elements of an array represent students’ exam grades, the instructor might wish to total the elements of the array, then calculate the class average for the exam. Figure 7.3 sums the values contained in a 10-element integer array named values and displays the result in sumLabel. © by Pearson Education, Inc. All Rights Reserved.

26 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

27 7.5 Summing the Elements of an Array
Line 8 declares, allocates and initializes the 10-element array values. Line 13, in the body of the For statement, performs the addition. Alternatively, the values supplied as initializers for array could have been read into the program. For example, the user could enter the values through a TextBox, or the values could be read from a file on disk. Information about reading values from a file can be found in Chapter 8, Files. © by Pearson Education, Inc. All Rights Reserved.

28 7.6 Using Arrays to Analyze Survey Results
Our next example uses arrays to summarize data collected in a survey. Consider the following problem statement: Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses in an integer array and determine the frequency of each rating. This is a typical array-processing application (Fig. 7.4). We wish to summarize the number of responses of each type (that is, 1–5). Array responses (lines 9–10) is a 20-element integer array containing the students’ survey responses. © by Pearson Education, Inc. All Rights Reserved.

29 7.6 Using Arrays to Analyze Survey Results
The last value in the array is intentionally an incorrect response (14). When a Visual Basic program executes, array element indices are checked for validity—all indices must be greater than or equal to 0 and less than the length of the array. Any attempt to access an element outside that range of indices results in a runtime error that is known as an IndexOutOfRangeException. At the end of this section, we’ll discuss the invalid response value, demonstrate array bounds checking and introduce Visual Basic’s exception-handling mechanism, which can be used to detect and handle an IndexOutOfRangeException. © by Pearson Education, Inc. All Rights Reserved.

30 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

31 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

32 7.6 Using Arrays to Analyze Survey Results
The frequency Array We use the six-element array frequency (line 13) to count the number of occurrences of each response. Each element is used as a counter for one of the possible types of survey responses—frequency(1) counts the number of students who rated the food as 1, frequency(2) counts the number of students who rated the food as 2, and so on. The results are displayed in outputTextBox. © by Pearson Education, Inc. All Rights Reserved.

33 7.6 Using Arrays to Analyze Survey Results
Summarizing the Results The For statement (lines 16–25) reads the responses from the array responses one at a time and increments one of the five counters in the frequency array (frequency(1) to frequency(5); we ignore frequency(0) because the survey responses are limited to the range 1–5). The key statement in the loop appears in line 18. This statement increments the appropriate frequency counter as determined by the value of responses(answer). Let’s step through the first few iterations of the For statement: © by Pearson Education, Inc. All Rights Reserved.

34 7.6 Using Arrays to Analyze Survey Results
When the counter answer is 0, responses(answer) is the value of responses(0) (that is, 1—see line 10). In this case, frequency(responses(answer)) is interpreted as frequency(1), and the counter frequency(1) is incremented by one. To evaluate the expression, we begin with the value in the innermost set of parentheses (answer, currently 0). The value of answer is plugged into the expression, and the next set of parentheses (responses(answer)) is evaluated. That value is used as the index for the frequency array to determine which counter to increment (in this case, frequency(1)). © by Pearson Education, Inc. All Rights Reserved.

35 7.6 Using Arrays to Analyze Survey Results
The next time through the loop answer is 1, responses(answer) is the value of responses(1) (that is, 2—see line 10), so frequency(responses(answer)) is interpreted as frequency(2), causing frequency(2) to be incremented. When answer is 2, responses(answer) is the value of responses(2) (that is, 5—see line 10), so frequency(responses(answer)) is interpreted as frequency(5), causing frequency(5) to be incremented, and so on. © by Pearson Education, Inc. All Rights Reserved.

36 7.6 Using Arrays to Analyze Survey Results
Regardless of the number of responses processed in the survey, only a six-element array (in which we ignore element zero) is required to summarize the results, because all the correct response values are between 1 and 5, and the index values for a six-element array are 0–5. In the output in Fig. 7.4, the frequency column summarizes only 19 of the 20 values in the responses array—the last element of the array responses contains an incorrect response that was not counted. © by Pearson Education, Inc. All Rights Reserved.

37 7.6 Using Arrays to Analyze Survey Results
Exception Handling: Processing the Incorrect Response An exception indicates a problem that occurs while a program executes. The name “exception” suggests that the problem occurs infrequently—if the “rule” is that a statement normally executes correctly, then the problem represents the “exception to the rule.” Exception handling enables you to create fault-tolerant programs that can resolve (or handle) exceptions. © by Pearson Education, Inc. All Rights Reserved.

38 7.6 Using Arrays to Analyze Survey Results
In many cases, this allows a program to continue executing as if no problems were encountered. For example, the Student Poll application still displays results (Fig. 7.4(b)), even though one of the responses was out of range. More severe problems might prevent a program from continuing normal execution, instead requiring the program to notify the user of the problem, then terminate. When the runtime or a method detects a problem, such as an invalid array index or an invalid method argument, it throws an exception—that is, an exception occurs. © by Pearson Education, Inc. All Rights Reserved.

39 7.6 Using Arrays to Analyze Survey Results
The Try Statement To handle an exception, place any code that might throw an exception in a Try statement (lines 17–24). The Try block (lines 17–18) contains the code that might throw an exception, and the Catch block (lines 19–23) contains the code that handles the exception if one occurs. You can have many Catch blocks to handle different types of exceptions that might be thrown in the corresponding Try block. When line 18 correctly increments an element of the frequency array, lines 19–23 are ignored. The End Try keywords terminate a Try statement. © by Pearson Education, Inc. All Rights Reserved.

40 7.6 Using Arrays to Analyze Survey Results
Executing the Catch Block When the program encounters the value 14 in the responses array, it attempts to add 1 to frequency(14), which does not exist—the frequency array has only six elements. Because array bounds checking is performed at execution time, line 18 throws an IndexOutOfRangeException to notify the program of this problem. © by Pearson Education, Inc. All Rights Reserved.

41 7.6 Using Arrays to Analyze Survey Results
At this point the Try block terminates and the Catch block begins executing—if you declared any variables in the Try block, they’re now out of scope and are not accessible in the Catch block. The Catch block declares an exception parameter (ex) and a type (IndexOutOfRangeException)—the Catch block can handle exceptions of the specified type. Inside the Catch block, you can use the parameter’s identifier to interact with a caught exception object. © by Pearson Education, Inc. All Rights Reserved.

42 7.6 Using Arrays to Analyze Survey Results
Entering a Try Statement in the Code Editor When you create a Try statement in your own code, you begin by typing Try and pressing Enter. The IDE then generates the following code: Try Catch ex As Exception End Try which can catch any type of exception thrown in the Try block. We changed Exception to IndexOutOfRangeException—the type of exception that might occur in line 18. © by Pearson Education, Inc. All Rights Reserved.

43 7.6 Using Arrays to Analyze Survey Results
Message Property of the Exception Parameter When lines 19–23 catch the exception, the program displays a MessageBox indicating the problem that occurred. Line 21 uses the exception object’s Message property to get the error message that is stored in the exception object and display it in the MessageBox. Once the user dismisses the MessageBox, the exception is considered handled and the program continues with the next statement after the End Try keywords. In this example, Next (line 25) causes the program to continue with line 16. Chapter 16 includes a detailed treatment of exception handling. © by Pearson Education, Inc. All Rights Reserved.

44 7.7 Die-Rolling Program with an Array of Counters
In Chapter 6, we used a series of counters in our die- rolling program to track the number of occurrences of each face on a six-sided die. We indicated that we can do what we did in Fig. 6.14 in a more elegant way than using a Select…Case statement to write the dice-rolling program. An array version of this application is shown in Fig. 7.5. This new version uses the same GUI as the application in Fig. 6.14. © by Pearson Education, Inc. All Rights Reserved.

45 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

46 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

47 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

48 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

49 7.7 Die-Rolling Program with an Array of Counters
Lines 61–74 of Fig. 6.14 are replaced by line 55 of Fig. 7.5, which uses face’s value as the index for array frequency to determine which element should be incremented during each iteration of the loop. The random number calculation at line 46 produces numbers from 1 to 6 (the values for a six-sided die); thus, the frequency array must have seven elements so we can use the index values 1–6. © by Pearson Education, Inc. All Rights Reserved.

50 7.7 Die-Rolling Program with an Array of Counters
We ignore frequency element 0. Lines 37–41 replace lines 35–46 from Fig. 6.14. We can loop through array frequency; therefore, we do not have to enumerate each line of text to display in the TextBox, as we did in Fig. 6.14. Recall from Section 6.9 that the more you roll the dice, the closer each percentage should get to 16.66%, as shown in Fig. 7.5(b). © by Pearson Education, Inc. All Rights Reserved.

51 7.8  Case Study: Flag Quiz Let’s create an application that tests a student’s knowledge of the flags of various countries. Consider the following problem statement: A geography instructor would like to quiz students on their knowledge of the flags of various countries. The instructor has asked you to write an application that displays a flag and allows the student to select the corresponding country from a list. The application should inform the user of whether the answer is correct and display the next flag. The application should display a flag randomly chosen from those of Australia, Brazil, China, Italy, Russia, South Africa, Spain and the United States. When the application executes, a given flag should be displayed only once. © by Pearson Education, Inc. All Rights Reserved.

52 7.8  Case Study: Flag Quiz The application uses arrays to store information. One array stores the country names. Another stores Boolean values that help us determine whether a particular country’s flag has already been displayed, so that no flag is displayed more than once during a quiz. © by Pearson Education, Inc. All Rights Reserved.

53 7.8 Case Study: Flag Quiz Flag Quiz GUI
Figure 7.6 shows the application’s GUI. The flag images should be added to the project as image resources—you learned how to do this in Section 6.9. The images are located in the Images folder with this chapter’s examples. This application introduces the ComboBox control, which presents options in a drop-down list that opens when you click the down arrow at the right side of the control. A ComboBox combines features of a TextBox and a ListBox. © by Pearson Education, Inc. All Rights Reserved.

54 7.8  Case Study: Flag Quiz You can click the down arrow to display a list of predefined items. If you choose an item from this list, that item is displayed in the ComboBox. If the list contains more items than the drop-down list can display at one time, a vertical scrollbar appears. You may also type into the ComboBox control to locate an item. In this application, the user selects an answer from the ComboBox, then clicks the Submit Button to check if the selected country name is correct for the currently displayed flag. © by Pearson Education, Inc. All Rights Reserved.

55 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

56 7.8  Case Study: Flag Quiz ComboBox property DropDownStyle determines the ComboBox’s appearance. Value DropDownList specifies that the ComboBox is not editable (you cannot type text in its TextBox). In this ComboBox style, if you press the key that corresponds to the first letter of an item in the ComboBox, that item is selected and displayed in the ComboBox. If multiple items start with the same letter, pressing the key repeatedly cycles through the corresponding items. Set the ComboBox’s DropDownStyle property to DropDownList. © by Pearson Education, Inc. All Rights Reserved.

57 7.8  Case Study: Flag Quiz Then, set the ComboBox’s MaxDropDownItems property to 4, so that the drop-down list displays a maximum of four items at one time. We do this to demonstrate that a vertical scrollbar is added to the drop-down list to allow users to scroll through the remaining items. We show how to programmatically add items to the ComboBox shortly. Figure 7.7 shows the application’s code. © by Pearson Education, Inc. All Rights Reserved.

58 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

59 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

60 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

61 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

62 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

63 7.8 Case Study: Flag Quiz Instance Variables
Lines 5–6 create and initialize the array of Strings called countries. Each element is a String containing the name of a country. The compiler determines the size of the array (in this case, eight elements) based on the number of items in the initializer list. Line 7 creates the Random object that is used in method GetUniqueRandomNumber (lines 49–58). © by Pearson Education, Inc. All Rights Reserved.

64 7.8  Case Study: Flag Quiz Line 10 creates the Boolean array used, which helps us determine which of the countries have already been displayed in the quiz. We specify the upper bound of the array used by getting the upper bound of the array countries. By default, each of array used’s elements is set to False. Variable count (line 12) keeps track of the number of flags displayed so far, and variable country (line 13) stores the name of the country that corresponds to the currently displayed flag. © by Pearson Education, Inc. All Rights Reserved.

65 7.8 Case Study: Flag Quiz Method FlagQuiz_Load
When the application loads, method FlagQuiz_Load executes. ComboBox property DataSource (line 20) specifies the source of the items displayed in the ComboBox. In this case, the source is array countries. Line 22 calls method DisplayFlag (declared in lines 61– 71) to display the first flag. © by Pearson Education, Inc. All Rights Reserved.

66 7.8 Case Study: Flag Quiz Method submitButton_Click
When you click the Submit Button, method submitButton_Click (lines 26–46) determines whether the selected answer is correct and displays an appropriate message (lines 30–35). If all the flags have been displayed, line 38 indicates that the quiz is over and lines 39–40 disable the ComboBox and Button. Otherwise, the quiz continues. Line 42 calls method DisplayFlag to display the next flag. Line 43 uses ComboBox property SelectedIndex to select the item at index 0 in the ComboBox—ComboBoxes are indexed from 0 like arrays. © by Pearson Education, Inc. All Rights Reserved.

67 7.8 Case Study: Flag Quiz Method GetUniqueRandomNumber
Method GetUniqueRandomNumber (lines 49–58) uses a Do…Loop Until statement to choose a random number in the bounds of the used array. The loop performs this task until the value at used(randomNumber) is False, indicating that the corresponding country’s flag has not yet been displayed. Line 56 marks the flag as used. Line 57 returns the random number. © by Pearson Education, Inc. All Rights Reserved.

68 7.8 Case Study: Flag Quiz Method DisplayFlag
Method DisplayFlag (lines 61–71) calls method GetUniqueRandomNumber (line 63) to determine which flag to display. Line 65 uses that value as the index into the countries array and stores the current country’s name in the variable country. This variable is used in method submitButton_Click to determine whether the selected answer is correct. Lines 68–70 get the corresponding flag’s image resource and display it in the flagPictureBox. © by Pearson Education, Inc. All Rights Reserved.

69 7.8  Case Study: Flag Quiz Some of the country names in the countries array contain spaces. However, the image resource names do not. To use a country name to load the appropriate image resource, we remove any spaces in the country name by calling String method Replace on country. The first argument to this method is the substring that should be replaced throughout the original String and the second argument is the replacement substring. In this case, we’re replacing each space with the empty String (""). © by Pearson Education, Inc. All Rights Reserved.

70 7.9 Passing an Array to a Method
To pass an array argument to a method, specify the name of the array without using parentheses. For example, if array hourlyTemperatures has been declared as Dim hourlyTemperatures(24) As Integer the method call DisplayDayData(hourlyTemperatures) passes array hourlyTemperatures to method DisplayDayData. © by Pearson Education, Inc. All Rights Reserved.

71 7.9 Passing an Array to a Method
Every array object “knows” its own upper bound (that is, the value returned by the method GetUpperBound), so when you pass an array object to a method, you do not need to pass the upper bound of the array as a separate argument. For a method to receive an array through a method call, the method’s parameter list must specify that an array will be received. For example, the method header for DisplayDayData might be written as Sub DisplayDayData( ByVal temperatureData() As Integer) indicating that DisplayDayData expects to receive an Integer array in parameter temperatureData. © by Pearson Education, Inc. All Rights Reserved.

72 7.9 Passing an Array to a Method
Arrays always are passed by reference, so when you pass an array to method DisplayDayData, it can change the original array’s element values. Although entire arrays are always passed by reference, individual array elements can be passed by value or by reference like simple variables of that type. For instance, array element values of primitive types, such as Integer, can be passed either by value or by reference, depending on the method definition. To pass an array element to a method, use the indexed name of the array element as an argument in the method call. Figure 7.8 demonstrates the difference between passing an entire array and passing an array element. The results are displayed in outputTextBox. © by Pearson Education, Inc. All Rights Reserved.

73 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

74 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

75 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

76 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

77 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

78 7.9 Passing an Array to a Method
The For…Next statement in lines 16–18 displays the five elements of integer array array1 (line 9). Line 20 passes array1 to method ModifyArray (lines 47–51), which then multiplies each element by 2 (line 49). To illustrate that array1’s elements were modified in the called method (that is, as enabled by passing by reference), the For…Next statement in lines 25–27 displays the five elements of array1. As the output indicates, the elements of array1 are indeed modified by ModifyArray. © by Pearson Education, Inc. All Rights Reserved.

79 7.9 Passing an Array to a Method
Lines 29–32 display the value of array1(3) before the call to ModifyElementByVal. Line 34 invokes method ModifyElementByVal (lines 55–61) and passes array1(3). When array1(3) is passed by value, the Integer value in position 3 of array array1 (now an 8) is copied and is passed to method ModifyElementByVal, where it becomes the value of parameter element. Method ModifyElementByVal then multiplies element by 2 (line 58). The parameter element of ModifyElementByVal is a local variable that is destroyed when the method terminates. © by Pearson Education, Inc. All Rights Reserved.

80 7.9 Passing an Array to a Method
Thus, when control is returned to Main, the unmodified value of array1(3) is displayed. Lines 37–43 demonstrate the effects of method ModifyElementByRef (lines 65–71). This method performs the same calculation as ModifyElementByVal, multiplying element by 2. In this case, array1(3) is passed by reference, meaning that the value of array1(3) displayed (lines 42–43) is the same as the value calculated in the method (that is, the original value in the caller is modified by the called method). © by Pearson Education, Inc. All Rights Reserved.

81 7.10 For Each…Next Repetition Statement
The For Each…Next repetition statement iterates through the values in a data structure, such as an array, without using a loop counter. For Each…Next behaves like a For…Next statement that iterates through the range of indices from 0 to the value returned by GetUpperBound(0). Instead of a counter, For Each…Next uses a variable to represent the value of each element. In this example, we’ll use the For Each…Next statement to determine the minimum value in a one-dimensional array of grades. The GUI for the application is shown in Fig. 7.9 and the code is shown in Fig. 7.10. © by Pearson Education, Inc. All Rights Reserved.

82 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

83 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

84 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

85 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

86 7.10 For Each…Next Repetition Statement
When the user clicks the Create Grades Button, method createGradesButton_Click (lines 8– 21) creates 10 random grade values in the range 0–99 and places them in the gradesListBox. When the user clicks the Find Smallest Button, method findSmallestButton_Click (lines 24– 38) uses a For Each…Next statement to find the lowest grade. The header of the For Each repetition statement (line 30) specifies an Integer variable (grade) and an array (gradesArray). © by Pearson Education, Inc. All Rights Reserved.

87 7.10 For Each…Next Repetition Statement
The type of variable grade is determined from the type of the elements in gradesArray, though you can also declare the variable’s type explicitly as in For Each grade As Integer In gradesArray The For Each statement iterates through all the elements in gradesArray, sequentially assigning each value to variable grade. The values are compared to variable lowGrade (line 31), which stores the lowest grade in the array. © by Pearson Education, Inc. All Rights Reserved.

88 7.10 For Each…Next Repetition Statement
The repetition of the For Each…Next statement begins with the element whose index is zero, iterating through all the elements. In this case, grade takes on the successive values that are stored in gradesArray and displayed in the gradesListBox. When all the grades have been processed, lowGrade is displayed (line 36). Although many array calculations are handled best with a counter, For Each is useful when you wish to process all of an array’s elements and do not need to access the index values in the loop’s body. © by Pearson Education, Inc. All Rights Reserved.

89 7.11 Sorting an Array with Method Sort of Class Array
Sorting data (that is, arranging the data in ascending or descending order) is one of the most popular computing applications. For example, a bank sorts all checks by account number, so that it can prepare individual bank statements at the end of each month. Telephone companies sort their lists of accounts by last name and, within last-name listings, by first name, to make it easy to find phone numbers. © by Pearson Education, Inc. All Rights Reserved.

90 7.11 Sorting an Array with Method Sort of Class Array
Arrays have the methods and properties of class Array in namespace System. Class Array provides methods for creating, modifying, sorting and searching arrays. By default, Array method Sort sorts an array’s elements into ascending order. The next application (GUI in Fig. 7.11 and code in Fig. 7.12) demonstrates method Sort by sorting an array of 10 randomly generated elements (which may contain duplicates). © by Pearson Education, Inc. All Rights Reserved.

91 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

92 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

93 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

94 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

95 7.11 Sorting an Array with Method Sort of Class Array
Method createDataButton_Click (lines 8–21) assigns 10 random values to the elements of integerArray and displays the contents of the array in the originalValuesTextBox. Method sortButton_Click (lines 24–35) sorts integerArray by calling Array.Sort, which takes an array as its argument and sorts the elements in the array in ascending order. © by Pearson Education, Inc. All Rights Reserved.

96 7.11 Sorting an Array with Method Sort of Class Array
Sorting in Descending Order To sort an array in descending order, first call method Sort to sort the array, then call Array.Reverse with the array as an argument to reverse the order of the elements in the array. Exercise 7.14 asks you to modify this program to display an array’s values in both ascending and descending order. © by Pearson Education, Inc. All Rights Reserved.


Download ppt "Visual Basic 2010 How to Program"

Similar presentations


Ads by Google