Presentation is loading. Please wait.

Presentation is loading. Please wait.

Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Similar presentations


Presentation on theme: "Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved."— Presentation transcript:

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

2

3  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.  The highest position number in array (also called the array’s upper bound), which is 1 less than the number of elements in the array. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

4

5  The array C (11) contains 12 elements, any one of which can be referred to by giving the name of the array C 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). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

6  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). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

7  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 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

8  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

9  The following statement can be used to declare an array: Dim c(11) As Integer ‘ An array of 12 elements  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

10  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

11  You can follow an array declaration with an equal sign and an initialized 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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

12  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 } © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

13  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

14  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.  Line 13 declares and allocates array2, whose size is determined by the expression array1.GetUpperBound(0). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

15

16  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). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

17

18  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

19

20  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). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

21

22  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

23

24  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

25  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

26  The Try Statement  To handle an exception, place any code that might throw an exception in a Try statement.  The Try block contains the code that might throw an exception.   The Catch block contains the code that handles the exception if one occurs.  The End Try keywords terminate a Try statement. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

27  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

28  At this point the Try block terminates and the Catch block begins executing.  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

29  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

30  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

31  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)  It indicates that DisplayDayData expects to receive an Integer array in parameter temperatureData. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

32  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.  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

33

34

35

36

37

38  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 Fig. 7.9 & 7.10, we’ll use the For Each … Next statement to determine the minimum value in a one- dimensional array of grades. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

39

40

41

42

43  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 demonstrates method Sort by sorting an array of 10 randomly generated elements (which may contain duplicates). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

44

45

46

47

48  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

49  Often it’s necessary to determine whether an array contains a value that matches a certain key value.  The process of locating a particular element value in an array is called searching.  There are two searching techniques—the simple linear search and the more efficient (but more complex) binary search. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

50  The Array method BinarySearch to perform a binary search for a key value: Dim index As Integer = Array.BinarySearch(searchData, searchKey)  The method receives two arguments—the sorted integer array searchData (the array to search) and integer searchKey (the search key).  If the value is found, method BinarySearch returns the index of the search key; otherwise, it returns a negative number. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

51  The arrays we’ve studied so far are one-dimensional arrays—they contain a list of values and use only one index to access each element.  We can have multidimensional arrays, which require two or more indices to identify particular elements.  A two-dimensional array—also known as rectangular arrays—which are often used to represent tables of values consisting of data arranged in rows and columns. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

52

53  Each row is the same size, and each column is the same size (hence the term “rectangular”).  To identify a particular table element, we specify two indices—by convention, the first identifies the element’s row, the second the element’s column.  A rectangular array with m rows and n columns is called an m-by-n array. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

54  Every element in array a is identified in by an element name of the form a(i, j), where a is the name of the array and i and j are the indices that uniquely identify the row and column, respectively, of each element in array a.  Array indices are zero based, so the names of the elements in row 0 all have a first index of 0 ; the names of the elements in column 3 all have a second index of 3. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

55  A two-dimensional rectangular array numbers with two rows and two columns can be declared and initialized with  ' numbers in a 2 by 2 array Dim numbers(1, 1) As Integer numbers(0, 0) = 1 ' leftmost element in row 0 numbers(0, 1) = 2 ' rightmost element in row 0 numbers(1, 0) = 3 ' leftmost element in row 1 numbers(1, 1) = 4 ' rightmost element in row 1  Alternatively, the initialization can be written on one line, as shown with and without local type inference below:  Dim numbers = {{1, 2}, {3, 4}} Dim numbers(,) As Integer = {{1, 2}, {3, 4}} © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

56  The values are grouped by row in braces, with 1 and 2 initializing numbers(0, 0) and numbers(0, 1), respectively, and 3 and 4 initializing numbers(1, 0) and numbers(1, 1), respectively.  The compiler determines the number of rows by counting the number of sub-initializer lists (represented by the sets of data in curly braces) in the main initializer list.  Then the compiler determines the number of columns in each row by counting the number of initializer values in the subinitializer list for that row.  The subinitializer lists must have the same number of elements for each row. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

57 7.14 Manipulating Rectangular Arrays

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

59  An array’s size cannot be changed, so a new array must be created if you need to change the size of an existing array.  The ReDim statement “resizes” an array at execution time by creating a new array and assigning it to the specified array variable.  The values in the array can also be reserved using the keyword Preserve.  Figure 7.28 demonstrates the ReDim statement. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

60 Initial & Resizing without preserving values

61 © 1992-2011 by Pearson Education, Inc. All Rights Reserved. Resizing with preserving values

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


Download ppt "Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved."

Similar presentations


Ads by Google