|< Day Day Up >|
Looping statements execute statements more than once.
The For statement executes statements a set number of times. The statement begins with the keyword For , followed by a variable that will contain the value of the current iteration; this variable is called the loop control variable . The loop control variable is followed by the = assignment operator, the lower bound of the loop, the keyword To , and then the upper bound of the loop. A For loop statement is closed by a Next statement.
When a For statement begins, the lower bound is assigned to the loop control variable. All of the statements in the For loop are executed, and then the loop control variable is incremented by 1. If the loop control variable is greater than the upper bound, the loop ends. The following example prints the values 1 through 10.
Dim x As Integer For x = 1 To 10 Console.WriteLine("x = " & x) Next x
For compactness, the loop control variable may be declared within the For statement itself; otherwise , the name must refer to a variable in an enclosing block. For example, the previous loop could have been written as follows .
For x As Integer = 1 To 10 Console.WriteLine("x = " & x) Next x
The Next statement may be followed by the name of the loop control variable of the For loop that the Next closes ”the variable name must match the immediately containing For loop. A Next statement may also close multiple For loops by listing all the loop control variables in a comma-delimited list. In that case, the loop control variables close the For loops in order from left to right. For example:
Dim x, y, z As Integer For x = 1 To 10 For y = 1 To 10 For z = 1 to 10 Console.WriteLine(x + y + z) Next z, y, x
For example, it is suggested that the previous example be written instead as follows.
Dim x, y, z As Integer For x = 1 To 10 For y = 1 To 10 For z = 1 to 10 Console.WriteLine(x + y + z) Next z Next y Next x
A For loop may also specify how much each loop should increment the loop control variable. The default is 1, but the keyword Step and a value can be added after the upper bound to specify what the step should be. This allows any numeric value, including negative values. The following example prints the values 10 down to 1.
Dim x As Integer For x = 10 To 1 Step -1 Console.WriteLine("x = " & x) Next
The loop control variable may be of any numeric type or of type Object . The bounds and the step value (if any) must be convertible to the type of the loop control variable. If the loop control variable's type is Object , the widest type of the values will be used as the type for the loop.
For Each Statement
The For Each statement loops through the elements in a collection . A collection can be any type that stores a set of values ”an array is an example of a collection, and the class Collection is another one. The statement begins with the keywords For Each , followed by an expression that is used as the loop control variable. The loop control variable will contain the current element of the collection being iterated through. The loop control variable is followed by the keyword In and an expression that must be a collection type.
When a For Each loop begins, the loop control variable is initialized with the first element in the collection. After the statements in the loop are executed, the loop control variable is updated with the next item in the collection. If there are no more items in the collection, the loop ends. The following example fills an array with the numbers 1 through 10 and then prints them.
Dim x(10) As Integer Dim y As Integer Dim z As Integer For y = 1 To 10 x(y) = y Next y For Each z In x Console.WriteLine(z) Next z
For compactness, the loop control variable may be declared within the For Each statement itself; otherwise, the name must refer to a variable in an enclosing block. For example, the previous loop could have been written as follows.
For Each z As Integer In x Console.WriteLine(z) Next z
Because there is no place to put a conversion operator when the type of the loop control variable is not the same type as the collection type, a For Each statement will convert from the element type of the collection to the loop control variable without an error even if Option Strict is on. If a value cannot be converted, a runtime exception will occur.
While and Do Statements
The While and Do statements allow unbounded looping ”both statements will continue looping until some user -defined condition evaluates to True . The While statement is the simpler of the two statements; it starts with the keyword While and an expression that is evaluated at the beginning of each loop. If the expression evaluates to True , the loop continues; if it evaluates to False , the loop ends. A While statement ends with an End While statement. The following example prints the values 1 through 10.
Dim x As Integer = 10 While x > 0 Console.WriteLine("x = " & x) x -= 1 End While
A Do loop offers more flexibility in how and when the loop condition is tested . The Do statement takes one of two forms. One form begins with the keyword Do , followed by either Until or While and an expression, and ends with the Loop statement. In this form, the expression is evaluated at the beginning of the loop. If the keyword Until is specified, the loop continues if the expression evaluates to False ; if the keyword While is specified, the loop continues if the expression evaluates to True .
Dim x As Integer = 10 Do While x > 0 Console.WriteLine("x = " & x) x -= 1 Loop Do Until x = 11 Console.WriteLine("x = " & x) x += 1 Loop
The second form of Do loop moves the conditional expression to the Loop statement. In this form, the expression is evaluated at the end of the loop rather than the beginning.
Dim x As Integer = 10 Do Console.WriteLine("x = " & x) x -= 1 Loop While x > 0 Do Console.WriteLine("x = " & x) x += 1 Loop Until x = 11
In this example, each loop will always execute at least once, whereas the loops in the previous example may never execute if the condition is not satisfied.
A collection type follows a design pattern that allows its members to be enumerated. Only collection types can be enumerated by a For Each statement. A collection type is any type that implements the interface System.IEnumerable or satisfies the following conditions.
Just implementing the interface IEnumerable is sufficient to make a type a collection type, but a collection type that only implements IEnumerable suffers from the fact that IEnumerable uses the type Object as its element type. This means that every time a value is fetched from the collection, it must be converted to its actual type. By satisfying the three conditions listed earlier instead, a class can implement the collection methods in a strongly typed way. The following class is an example of a collection type that stores Integer values.
Class IntegerCollection Class IntegerEnumerator Private Collection As IntegerCollection Private Index As Integer = -1 Public Sub New(ByVal Collection As IntegerCollection) Me.Collection = Collection End Sub Public Sub Reset() Index = -1 End Sub Public Function MoveNext() As Boolean If Index < Collection.Length Then Index += 1 End If Return (Index = Collection.Length) End Function Public ReadOnly Property Current() As Integer Get If Index = -1 OrElse Index = Collection.Length Then Throw New InvalidOperationException() End If Return Collection(Index) End Get End Property End Class Private Values() As Integer Public Sub New(ByVal Values() As Integer) Me.Values = Values End Sub Public ReadOnly Property Length() As Integer Get Return Values.Length End Get End Property Public Function GetEnumerator As IntegerEnumerator Return New IntegerEnumerator(Me) End Function End Class
Because many methods in the Framework take classes that implement IEnumerable , it is recommended that IEnumerable be implemented even if the strongly typed pattern is being used.
When a For Each loop executes, the collection's methods are called as follows: When the loop begins, GetEnumerator is called on the loop expression, and the returned enumerator is stored in a temporary variable. Then at the beginning of each loop, MoveNext is called on the enumerator. If the function returns False , the loop terminates. If the function returns True , the Current property is retrieved and assigned to the loop control variable; then the loop block executes. When the Next statement is reached, execution returns to the top of the loop.
|< Day Day Up >|