Section 8.7. For Each...Next Repetition Statement


8.7. For Each...Next Repetition Statement

Visual Basic provides the For Each...Next repetition statement for iterating through the values in a data structure, such as an array, without using a loop counter. When used with one-dimensional arrays, 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. The program in Fig. 8.12 uses the For Each...Next statement to determine the minimum value in a one-dimensional array of grades.

Figure 8.12. Using For Each...Next with an array.

  1  ' Fig. 8.12: ForEach.vb  2  ' Program uses For Each...Next to find the minimum grade.  3  Module ForEach  4     Sub Main()  5        Dim gradeArray As Integer() = New Integer() _  6           {77, 68, 86, 73, 98, 87, 89, 81, 70, 90, 86, 81}  7        Dim lowGrade As Integer = 100  8  9        ' use For Each...Next to find the minimum grade 10        For Each grade As Integer In gradeArray         11           If grade < lowGrade Then                     12              lowGrade = grade                          13           End If                                       14        Next                                            15 16        Console.WriteLine("The minimum grade is: {0}", lowGrade) 17     End Sub ' Main 18  End Module ' ForEach 

 The  minimum grade is: 68 



The header of the For Each repetition statement (line 10) specifies an Integer variable (grade) and an array (gradeArray). The For Each statement iterates through all the elements in gradeArray, sequentially assigning each value to variable grade. The values are compared to variable lowGrade (line 11), which stores the lowest grade in the array.

For one-dimensional arrays, the repetition of the For Each...Next statement begins with the element whose index is zero, then iterates through all the indices. In this case, grade takes on the successive values as they are ordered in the initializer list in line 6. When all the grades have been processed, lowGrade is displayed. Although many array calculations are handled best with a counter, For Each is useful when the indices of the elements are not important.



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