Section 8.4. Examples Using Arrays


8.4. Examples Using Arrays

This section presents several examples that demonstrate the declaration, allocation and initialization of arrays, as well as various common manipulations of array elements. The examples in this section use arrays that contain elements of type Integer.

8.4.1. Allocating an Array

The program in Fig. 8.2 uses the New operator to allocate an array of 10 Integer elements, which are initially zero (the default value for Integer variables). The program displays the array elements in tabular format in a console window.

Figure 8.2. Creating an array.

  1  ' Fig. 8.2: CreateArray.vb  2  ' Declaring and allocating  an array.  3  Module CreateArray  4     Sub Main()  5        Dim array As Integer() ' declare array variable  6  7        ' allocate memory for 10-element array using explicit array bounds  8        array = New Integer(0 To 9) {}                                      9 10        Console.WriteLine("Index " & vbTab & "Value") 11 12        ' display values in array                      13        For i As Integer = 0 To array.GetUpperBound(0) 14           Console.WriteLine(i & vbTab & array(i))     15        Next                                           16 17        Console.WriteLine(vbCrLf & "The array contains " & _ 18           array.Length & " elements.") 19      End Sub ' Main 20   End Module ' CreateArray 

 Index    Value 0        0 1        0 2        0 3        0 4        0 5        0 6        0 7        0 8        0 9        0 The array contains 10 elements. 



Line 5 declares arraya variable capable of storing a reference to an array of Integers. Line 8 allocates an array of 10 elements (with explicit array bounds 0 to 9) using New and assigns it to array. Line 10 displays the headings for the columns. The columns represent the index for each array element and the value of each array element, respectively.

Lines 1315 use a For statement to display the index number (i) and the value of each array element (array(i)). We use zero-based counting (recall that array indices start at 0), so that the loop accesses every array element. Also note, in the header of the For statement, the expression array.GetUpperBound(0), used to retrieve the upper bound of the array (in this case, 9). The Length property (line 18) returns the number of elements in the array.

8.4.2. Initializing the Values in an Array

The program in Fig. 8.3 creates two integer arrays of 10 elements each and sets the values of the elements, using an initializer list and a For statement, respectively. The arrays are displayed in tabular format.

Figure 8.3. Initializing array elements with an array initializer and a For statement.

  1  ' Fig. 8.3: InitArray.vb  2  ' Initializing arrays.  3  Module InitArray  4     Sub Main()  5        ' initializer list specifies the number of elements  6        ' and the value of each element                      7        Dim array1 As Integer() = New Integer() _            8           {32, 27, 64, 18, 95, 14, 90, 70, 60, 37}          9 10        ' allocate array2 based on length of array1                       11        Dim array2 As Integer() = New Integer(array1.GetUpperBound(0)) {} 12 13        ' set values in array2 by a calculation 14        For i As Integer = 0 To array2.GetUpperBound(0) 15          array2(i) = 2 + 2 * i ' generate 2, 4, 6, ..., 20 16        Next 17 18        Console.WriteLine("Index " & vbTab & "Array1" & vbTab & "Array2") 19 20        ' display values for both arrays side by side 21        For i As Integer = 0 To array1.GetUpperBound(0) 22           Console.WriteLine(i & vbTab & array1(i) & vbTab & array2(i)) 23        Next 24     End Sub ' Main 25  End Module ' InitArray 

 Index   Array1  Array2 0       32      2 1       27      4 2       64      6 3       18      8 4       95      10 5       14      12 6       90      14 7       70      16 8       60      18 9       37      20 



Lines 78 combine the declaration and allocation of array1 into one statement, allocate the 10 elements of array1 with New, and initialize the values in array1, using an initializer list. Line 11 declares and allocates array2, whose size is determined by the expression array1.GetUpperBound(0), meaning that array1 and array2, in this particular program, have the same upper bound (9) and the same size (10).

The For statement in lines 1416 initializes the elements in array2 to the even integers 2, 4, 6, ..., 20. 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 2123 displays the values in the arrays.

8.4.3. Summing the Elements of an Array

Often, the elements of an array represent a series of values that are employed in a calculation. For example, if the elements of an array represent a group of students' exam grades, the instructor might wish to total the elements of the array, then calculate the class average for the exam. The program in Fig. 8.4 sums the values contained in a 10-element integer array.

Figure 8.4. Computing the sum of the elements in an array .

  1  ' Fig. 8.4: SumArray.vb  2  ' Computing the sum of the elements in an array.  3  Module SumArray  4     Sub Main()  5        Dim array As Integer() = New Integer() _  6           {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}       7        Dim total As Integer = 0  8  9        ' sum the array element values                 10        For i As Integer = 0 To array.GetUpperBound(0) 11           total += array(i)                           12        Next                                          13 14        Console.WriteLine("Total of array elements: " & total) 15     End Sub ' Main 16  End Module ' SumArray 

 Total of array elements: 55 



Lines 56 declare, allocate and initialize the 10-element array array. Line 11, 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 into a program from a file can be found in Chapter 18, Files and Streams.

8.4.4. Using Arrays to Analyze Survey Results

Our next example uses arrays to summarize data collected in a survey. Consider the following problem statement:

Forty students were asked to rate on a scale of 1 to 10 the quality of the food in the student cafeteria, with 1 being "awful" and 10 being "excellent." Place the 40 responses in an integer array and determine the frequency of each rating.

This exercise represents a typical array-processing application (Fig. 8.5). We wish to summarize the number of responses of each type (i.e., 110). Array responses (lines 68) is a 40-element integer array containing the students' responses to the survey. Using an 11-element array frequency, we can count the number of occurrences of each response. We ignore frequency(0) because it is more natural to have a survey response of 1 result in frequency(1) being incremented rather than incrementing frequency(0). We can use each response directly as an index on the frequency array. Each element of the array is used as a counter for one of the possible types of survey responsesfrequency(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.

Figure 8.5. Simple student-poll analysis program.

  1  ' Fig. 8.5: StudentPoll.vb  2  ' Using arrays to display poll results.  3  Module StudentPoll  4     Sub Main()  5        ' student response array (more typically, input at run time)  6        Dim responses As Integer() = New Integer() _  7           {1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, _  8           7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10}  9 10        ' response frequency array (indices 0 through 10) 11        Dim frequency As Integer() = New Integer(10) {} 12 13        ' count frequencies                                     14        For answer As Integer = 0 To responses.GetUpperBound(0) 15           frequency(responses(answer)) += 1                    16        Next                                                    17 18        Console.WriteLine("Rating " & vbTab & "Frequency") 19 20        ' display output, ignore element 0 of frequency 21        For rating As Integer = 1 To frequency.GetUpperBound(0) 22           Console.WriteLine(rating & vbTab & frequency(rating)) 23        Next 24     End Sub ' Main 25  End Module ' StudentPoll 

 Rating  Frequency 1       2 2       2 3       2 4       2 5       5 6       11 7       5 8       7 9       1 10      3 



The For statement (lines 1416) reads the responses from the array responses one at a time and increments one of the 10 counters in the frequency array (frequency(1) to frequency(10); we ignore frequency(0) because the survey responses are limited to the range 110). The key statement in the loop appears in line 15. This statement increments the appropriate frequency counter as determined by the value of responses(answer).

Let us consider several iterations of the For statement. When the counter answer is 0, responses(answer) is the value of responses(0) (i.e., 1see line 7). Therefore, frequency(responses(answer)) is interpreted as frequency(1), meaning that the counter frequency(1) is incremented by one. In evaluating the expression frequency(responses(answer)), Visual Basic starts with the value in the innermost set of parentheses (answer, currently 0). The value of answer is plugged into the expression, and Visual Basic evaluates the next set of parentheses (responses(answer)). That value is used as the index for the frequency array to determine which counter to increment (in this case, the 1 counter).

When answer is 1, responses(answer) is the value of responses(1) (i.e., 2see line 7). As a result, frequency(responses(answer)) is interpreted as frequency(2), causing array element 2 to be incremented.

When answer is 2, responses(answer) is the value of responses(2) (i.e., 6see line 7), so frequency(responses(answer)) is interpreted as frequency(6), causing array element 6 to be incremented, and so on. Note that, regardless of the number of responses processed in the survey, only an 11-element array (in which we ignore element zero) is required to summarize the results, because all the response values are between 1 and 10, and the index values for an 11-element array are 010. Note that, in the output in Fig. 8.5, the numbers in the frequency column correctly total 40 (the elements of the frequency array were initialized to zero when the array was allocated with New).

If the data contained the out-of-range value 13, the program would attempt to add 1 to frequency(13). This is outside the bounds of the array. In languages like C and C++, such a dangerous out-of-bounds reference would be allowed. The program would "walk" past the end of the array to where it thought element number 13 was located and would add 1 to whatever happened to be stored at that memory location. This could modify another variable in the program, possibly causing incorrect results or even premature program termination. Visual Basic provides mechanisms that prevent accessing elements outside the bounds of arrays.

Common Programming Error 8.3

Referencing an element outside the array bounds is a runtime error.


Error-Prevention Tip 8.1

When a program is executed, array element indices are checked for validity (i.e., all indices must be greater than or equal to 0 and less than the length of the array). If an attempt is made to use an invalid index to access an element, Visual Basic generates an IndexOutOfRangeException exception. Exceptions are discussed in detail in Chapter 12, Exception Handling.


Error-Prevention Tip 8.2

When looping through an array, the array index should remain between 0 and the upper bound of the array (i.e., the value returned by method GetUpperBound). The initial and final values used in the repetition statement should prevent accessing elements outside this range.


8.4.5. Using Bar Charts to Display Array Data Graphically

Many programs present data to users in a visual or graphical format. For example, numeric values are often displayed as bars in a bar chart. In such a chart, longer bars represent proportionally larger numeric values. Figure 8.6 displays numeric data graphically by creating a bar chart that shows each numeric value as a bar of asterisks (*).

Figure 8.6. Bar chart printing program.

  1   ' Fig. 8.6: BarChart.vb  2   ' Using data to create bar chart.  3   Module BarChart  4      Sub Main()  5         ' create data array  6         Dim array1 As Integer() = New Integer() _  7            {19, 3, 15, 7, 11, 9, 13, 5, 17, 1}  8  9         Console.WriteLIne("Element " & "Value " & vbTab & "Bar Chart") 10 11        ' display a bar of the bar chart for each element in the array 12        For i As Integer = 0 To array1.GetUpperBound(0)                13           Console.Write(i & vbTab & array1(i) & vbTab)                14         15           For j As Integer = 1 To array1(i)                           16              Console.Write("*") ' display one asterisk                17           Next                                                        18         19           Console.WriteLine()                                        20        Next                                                           21     End Sub ' Main 22  End Module ' BarChart 

 Element Value   Bar Chart 0       19      ******************* 1       3       *** 2       15      *************** 3       7       ******* 4       11      *********** 5       9       ********* 6       13      ************* 7       5       ***** 8       17      ***************** 9       1       * 



The program reads numbers from an array and graphs the information as a bar chart. Each number is printed, and a bar consisting of the corresponding number of asterisks is displayed beside the number. The nested For loops (lines 1220) display the bars. Note the end value (array1(i)) of the inner For statement at line 15. Each time the inner For statement is reached (line 15), it counts from 1 to array1(i), using a value in array1 to determine the final value of the control variable jthe number of asterisks to display.

8.4.6. Using the Elements of an Array as Counters

Sometimes programs use a series of counter variables to summarize data, such as the results of a survey. In Chapter 7, 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 as the program rolled the die 12 times. We indicated that there is a more elegant way of doing what we did in Fig. 7.16 for writing the dice-rolling program. An array version of this application is shown in Fig. 8.7. The images of the dice are included in this example's directory.

Figure 8.7. Using arrays to eliminate a Select Case statement.

  1  ' Fig. 8.7: RollDie.vb  2  ' Rolling 12 dice with frequency chart.  3  Imports System.IO  4  5  Public Class FrmRollDie  6     Dim randomNumber As Random = New Random()  7     Dim frequency As Integer() = New Integer(6) {}  8  9     ' event handler for btnRoll button 10     Private Sub btnRoll_Click(ByVal sender As System.Object, _ 11        ByVal e As System.EventArgs) Handles btnRoll.Click 12 13        ' pass PictureBox to a method that assigns a face to each die 14        DisplayDie(picDie1) 15        DisplayDie(picDie2) 16        DisplayDie(picDie3) 17        DisplayDie(picDie4) 18        DisplayDie(picDie5) 19        DisplayDie(picDie6) 20        DisplayDie(picDie7) 21        DisplayDie(picDie8) 22        DisplayDie(picDie9) 23        DisplayDie(picDie10) 24        DisplayDie(picDie11) 25        DisplayDie(picDie12) 26 27        Dim total As Double = 0 28 29        ' total the die faces (used in percentage calculations) 30        For i As Integer = 1 To frequency.GetUpperBound(0)      31           total += frequency(i)                                32        Next                                                    33 34        txtDisplay.Text = "Face" & vbTab & "Frequency" & _ 35           vbTab & "Percent" & vbCrLf 36 37        ' output frequency values                          38        For i As Integer = 1 To frequency.GetUpperBound(0) 39           txtDisplay.Text &= i & vbTab & frequency(i) & _ 40              vbTab & vbTab & String.Format("{0:N}", _     41              frequency(i) / total * 100) & "%" & vbCrLf   42        Next                                               43     End Sub ' btnRoll_Click 44 45     ' simulate roll, display proper image and increment frequency 46     Sub DisplayDie(ByVal picDie As PictureBox) 47        Dim face As Integer = 1 + randomNumber.Next(6) 48 49        ' set appropriate die image in Image property 50        picDie.Image = _ 51           Image.FromFile(Directory.GetCurrentDirectory & _ 52           "\Images\die" & face & ".png") 53        frequency(face) += 1 ' increment appropriate frequency counter 54     End Sub ' DisplayDie 55  End Class ' FrmRollDie 

Lines 6073 of Fig. 7.16 are replaced by line 53 of Fig. 8.7, 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 47 produces numbers from 1to 6 (the values for a six-sided die); thus, the frequency array must have seven elements to allow the index values 16. We ignore element 0 of array frequency. Lines 3442 replace lines 3649 from Fig. 7.16. We can loop through array frequency; therefore, we do not have to enumerate each line of text to display in the PictureBox, as we did in Fig. 7.16.



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