Section 8.12. Jagged Arrays


8.12. Jagged Arrays

Jagged arrays are maintained as arrays of arrays. Unlike rectangular arrays, rows in jagged arrays can be of different lengths. The program in Fig. 8.20 demonstrates the initialization of a jagged array (array1) and the use of nested For...Next loops to traverse the array.

Figure 8.20. Initializing a jagged array.

  1  ' Fig. 8.20: JaggedArray.vb  2  ' Initializing a jagged array.  3  Module JaggedArray  4     Sub Main()  5        ' create jagged array                                         6        Dim array1 As Integer()() = New Integer(2)(){}' three rows    7        array1(0) = New Integer() {1, 2} ' row 0 is a single array    8        array1(1) = New Integer() {3} ' row 1 is a single array       9        array1(2) = New Integer() {4, 5, 6} ' row 2 is a single array 10 11        Console.WriteLine("Values in jagged array1 by row are") 12 13        ' output array1 elements                              14        For i As Integer = 0 To array1.GetUpperBound(0)       15           For j As Integer = 0 To array1(i).GetUpperBound(0) 16              Console.Write(array1(i)(j) & " ")               17           Next                                               18         19           Console.WriteLine()                                20        Next                                                  21     End Sub ' Main 22  End Module ' JaggedArray 

 Values in jagged array1 by row are 1 2 3 4 5  6 



The program declares a jagged array in method Main. The declaration and allocation of the jagged array array1 (line 6) create a jagged array of three arrays (specified by the 2 in the first set of parentheses after keyword Integer). Lines 79 initialize each subarray so that the first subarray contains the values 1 and 2, the second contains the value 3 and the last contains the values 4, 5 and 6.

The nested For...Next statements in lines 1420 behave similarly to those that manipulate the rectangular array in Fig. 8.16. However, in a jagged array, the second dimension is actually an index into the one-dimensional array that represents the current row. In the example, the inner For...Next statement (lines 1517) uses GetUpperBound with the argument 0 to determine the number of columns in each row. In this case, we call GetUpperBound on a single rowarray(i). Arrays of more than two dimensions can be traversed using one nested For...Next statement for each dimension.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net