8.7. For Each...Next Repetition StatementVisual 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.
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. |