Vous êtes sur la page 1sur 20

Do { While | Until } condition [ statements ] [ Continue Do ] [ statements ] [ Exit Do ] [ statements ] Loop -orDo [ statements ] [ Continue Do ] [ statements ] [ Exit Do ] [ statements

] Loop { While | Until } condition

Parts
Term Do While Until condition statements Continue Do Exit Do Loop Definition Required. Starts the definition of the Do loop. Required unless Until is used. Repeat the loop until condition is False. Required unless While is used. Repeat the loop until condition is True.

Optional. Boolean expression. If condition is Nothing, Visual Basic treats it as

Optional. One or more statements that are repeated while, or until, condition Optional. Transfers control to the next iteration of the Do loop. Optional. Transfers control out of the Do loop. Required. Terminates the definition of the Do loop.

Remarks
Use a Do...Loop structure when you want to repeat a set of statements an indefinite number of times, until a condition is satisfied. If you want to repeat the statements a set number of times, the For...Next Statement is usually a better choice. You can use either While or Until to specify condition, but not both. You can test condition only one time, at either the start or the end of the loop. If you test condition at the start of the loop (in the Do statement), the loop might not run even one time. If you test at the end of the loop (in the Loop statement), the loop always runs at least one time. The condition usually results from a comparison of two values, but it can be any expression that evaluates to a Boolean Data Type (Visual Basic) value (True or False). This includes values of other data types, such as numeric types, that have been converted to Boolean. You can nest Do loops by putting one loop within another. You can also nest different kinds of control structures within each other. For more information, see Nested Control Structures (Visual Basic).

Exit Do

The Exit Do statement can provide an alternative way to exit a DoLoop. Exit Do transfers control immediately to the statement that follows the Loop statement. Exit Do is often used after some condition is evaluated, for example in an If...Then...Else structure. You might want to exit a loop if you detect a condition that makes it unnecessary or impossible to continue iterating, such as an erroneous value or a termination request. One use of Exit Do is to test for a condition that could cause anendless loop, which is a loop that could run a large or even infinite number of times. You can use Exit Do to escape the loop. You can include any number of Exit Do statements anywhere in a DoLoop. When used within nested Do loops, Exit Do transfers control out of the innermost loop and into the next higher level of nesting.

Example
In the following example, the statements in the loop continue to run until the index variable is greater than 10. The Until clause is at the end of the loop. VB

Dim index As Integer = 0 Do Debug.Write(index.ToString & " ") index += 1 Loop Until index > 10 Debug.WriteLine("") ' Output: 0 1 2 3 4 5 6 7 8 9 10
The following example uses a While clause instead of an Until clause, and condition is tested at the start of the loop instead of at the end. VB

Dim index As Integer = 0 Do While index <= 10 Debug.Write(index.ToString & " ") index += 1 Loop Debug.WriteLine("") ' Output: 0 1 2 3 4 5 6 7 8 9 10
In the following example, condition stops the loop when the index variable is greater than 100. The If statement in the loop, however, causes the Exit Do statement to stop the loop when the index variable is greater than 10. VB

Dim index As Integer = 0 Do While index <= 100 If index > 10 Then Exit Do End If Debug.Write(index.ToString & " ") index += 1 Loop Debug.WriteLine("") ' Output: 0 1 2 3 4 5 6 7 8 9 10
The following example reads all lines in a text file. The OpenText method opens the file and returns a StreamReader that reads the characters. In the Do...Loop condition, thePeek method of the StreamReader determines whether there are any additional characters. VB

Private Sub ShowText(ByVal textFilePath As String)

If System.IO.File.Exists(textFilePath) = False Then Debug.WriteLine("File Not Found: " & textFilePath) Else Dim sr As System.IO.StreamReader = System.IO.File.OpenText(textFilePath) Do While sr.Peek() >= 0 Debug.WriteLine(sr.ReadLine()) Loop sr.Close() End If End Sub The syntax of a For..Next loop has three components: a counter, a range, and a step. A basic for..next loop appears as follows: For X = 1 To 100 Step 2 Debug.Print X Next X In this example, X is the counter, "1 to 100" is the range, and "2" is the step. The variable reference in the Next part of the statement is optional and it is common practice to leave this out. There is no ambiguity in doing this if code is correctly indented. When a For..Next loop is initialized, the counter is set to the first number in the range; in this case, X is set to 1. The program then executes any code between the for and next statements normally. Upon reaching the next statement, the program returns to the for statement and increases the value of the counter by the step. In this instance, X will be increased to 3 on the second iteration, 5 on the third, etc. To change the amount by which the counter variable increases on each iteration, simply change the value of the step. For example, if you use a step 3, X will increase from 1 to 4, then to 7, 10, 13, and so on. When the step is not explicitly stated, 1 is used by default. (Note that the step can be a negative value. For instance, for X = 100 to 1 step -1 would decrease the value of X from 100 to 99 to 98, etc.) When X reaches the end of the range in the range (100 in the example above), the loop will cease to execute, and the program will continue to the code beyond the next statement. It is possible to edit the value of the counter variable within a for..next loop, although this is generally considered bad programming practice: For X = 1 To 100 Step 1 Debug.Print X X=7 Next While you may on rare occasions find good reasons to edit the counter in this manner, the example above illustrates one potential pitfall: Because X is set to 7 at the end of every iteration, this code creates an infinite loop. To avoid this and other unexpected behavior, use extreme caution when editing the counter variable! It is not required by the compiler that you specify the name of the loop variable in the Next statement but it will be checked by the compiler if you do, so it is a small help in writing correct programs.

For loop on list


Another very common situation is the need for a loop which enumerates every element of a list. The following sample code shows you how to do this: Dim v As Variant For Each v In list Debug.Print v Next The list is commonly a Collection or Array, but can be any other object that implements an enumerator. Note that the iterating variable has to be either a Variant, Object or class that matches the type of elements in the list. See Collections for more information on enumerators.

Do Loops
Do loops are a bit more flexible than For loops, but should generally only be used when necessary. Do loops come in the following formats: Do while Do until Loop while Loop until

While loops (both do while and loop while) will continue to execute as long as a certain conditional is true. An Until loop will loop as long as a certain condition is false, on the other hand. The only difference between putting either While or Until in the Do section or the Loop section, is that Do checks when the loop starts, and Loop check when the loops ends. An example of a basic loop is as follows: Do Debug.Print "hello" x=x+1 Loop Until x = 10 This loop will print hello several times, depending on the initial value of x. As you may have noticed, Do loops have no built in counters. However, they may be made manually as shown above. In this case, I chose x as my counter variable, and every time the loop execute, x increase itself by one. When X reaches 10, the loop will cease to execute. The advantage of Do loops is that you may exit at any time whenever any certain conditional is met. You may have it loop as long as a certain variable is false, or true, or as long as a variable remains in a certain range.

Endless loop: Do..Loop


The endless loop is a loop which never ends and the statements inside are repeated forever. Never is meant as a relative term here - if the computer is switched off then even endless loops will end very abruptly. Do Do_Something Loop

In Visual Basic you cannot label the loop but you can of course place a label just before it, inside it or just after it if you wish.

Loop with condition at the beginning: Do While..Loop


This loop has a condition at the beginning. The statements are repeated as long as the condition is met. If the condition is not met at the very beginning then the statements inside the loop are never executed. Do While X <= 5 X = Calculate_Something Loop

Loop with condition at the end: Do..Loop Until


This loop has a condition at the end and the statements are repeated until the condition is met. Since the check is at the end the statements are at least executed once. Do X = Calculate_Something Loop Until X > 5

Loop with condition in the middle:Do..Exit Do..Loop


Sometimes you need to first make a calculation and exit the loop when a certain criterion is met. However when the criterion is not met there is something else to be done. Hence you need a loop where the exit condition is in the middle. Do X = Calculate_Something If X > 10 then Exit Do End If Do_Something (X) Loop In Visual Basic you can also have more than one exit statement. You cannot exit named outer loops using Exit Do because Visual Basic does not provide named loops; you can of course use Goto instead to jump to a label that follows the outer loop.

While Loops
While loops are similar to Do loops except that the tested condition always appears at the top of the loop. If on the first entry into the loop block the condition is false, the contents of the loop are never executed. The condition is retested before every loop iteration. An example of a While loop is as follows: price = 2 While price < 64 Debug.Print "Price = " & price price = price ^ 2 Wend Debug.Print "Price = " & price & ": Too much for the market to bear!"

The While loop will run until the condition tests false - or until an "Exit While" statement is encountered.

Nested Loops
A nested loop is any type of loop inside an already existing loop. They can involve any type of loop. For this, we will use For loops. It is important to remember that the inner loop will execute its normal amount multiplied by how many times the outer loop runs. For example:.
You can use a For...Next statement to run a block of code, when you know how many repetitions you want. You can use a counter variable that increases or decreases with each repetition of the loop, like this:

For i=1 to 10 some code Next


The For statement specifies the counter variable (i) and its start and end values. The Nextstatement increases the counter variable (i) by one.

Step Keyword
Using the Step keyword, you can increase or decrease the counter variable by the value you specify. In the example below, the counter variable (i) is increased by two each time the loop repeats.

For i=2 To 10 Step 2 some code Next


To decrease the counter variable, you must use a negative Step value. You must specify an end value that is less than the start value. In the example below, the counter variable (i) is decreased by two each time the loop repeats.

For i=10 To 2 Step -2 some code Next Exit a For...Next


You can exit a For...Next statement with the Exit For keyword.

For Each...Next Loop


A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an array.

dim cars(2) cars(0)="Volvo" cars(1)="Saab" cars(2)="BMW" For Each x in cars document.write(x & "<br />") Next

Do...Loop
You can use Do...Loop statements to run a block of code when you do not know how many repetitions you want. The block of code is repeated while a condition is true or until a condition becomes true.

Repeating Code While a Condition is True


You use the While keyword to check a condition in a Do...Loop statement.

Do While i>10 some code Loop


If i equals 9, the code inside the loop above will never be executed.

Do some code Loop While i>10


The code inside this loop will be executed at least one time, even if i is less than 10.

Repeating Code Until a Condition Becomes True


You use the Until keyword to check a condition in a Do...Loop statement.

Do Until i=10 some code Loop


If i equals 10, the code inside the loop will never be executed.

Do some code Loop Until i=10


The code inside this loop will be executed at least one time, even if i is equal to 10.

Exit a Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.

Do Until i=10 i=i-1 If i<10 Then Exit Do Loop


The code inside this loop will be executed as long as i is different from 10, and as long as i is greater than 10.

For Each element [ As datatype ] In group [ statements ] [ Continue For ] [ statements ] [ Exit For ] [ statements ] Next [ element ]

Parts

Term element datatype group statements Continue For Exit For Next

Definition

Required in the For Each statement. Optional in the Next statement. Variable. U elements of the collection. Required if element isn't already declared. Data type of element.

Required. A variable with a type that's a collection type or Object. Refers to the c the statements are to be repeated.

Optional. One or more statements between For Each and Next that run on each i Optional. Transfers control to the start of the For Each loop. Optional. Transfers control out of the For Each loop. Required. Terminates the definition of the For Each loop.

Simple Example
Use a For Each...Next loop when you want to repeat a set of statements for each element of a collection or array.

Tip

A For...Next Statement (Visual Basic) works well when you can associate each iteration of a loop w determine that variable's initial and final values. However, when you are dealing with a collection, final values isn't meaningful, and you don't necessarily know how many elements the collection ha Each...Next loop is often a better choice.
In the following example, the For EachNext statement iterates through all the elements of a List collection. VB

' Create a list of strings by using a ' collection initializer. Dim lst As New List(Of String) _ From {"abc", "def", "ghi"} ' Iterate through the list. For Each item As String In lst Debug.Write(item & " ") Next Debug.WriteLine("") 'Output: abc def ghi
For more examples, see Collections (C# and Visual Basic) and Arrays in Visual Basic.

Nested Loops
You can nest For Each loops by putting one loop within another. The following example demonstrates nested For EachNext structures. VB

' Create lists of numbers and letters ' by using array initializers. Dim numbers() As Integer = {1, 4, 7} Dim letters() As String = {"a", "b", "c"} ' Iterate through the list by using nested loops. For Each number As Integer In numbers For Each letter As String In letters Debug.Write(number.ToString & letter & " ") Next Next Debug.WriteLine("") 'Output: 1a 1b 1c 4a 4b 4c 7a 7b 7c
When you nest loops, each loop must have a unique element variable. You can also nest different kinds of control structures within each other. For more information, see Nested Control Structures (Visual Basic).

Exit For and Continue For


The Exit For statement causes execution to exit the ForNext loop and transfers control to the statement that follows the Next statement. The Continue For statement transfers control immediately to the next iteration of the loop. For more information, see Continue Statement (Visual Basic). The following example shows how to use the Continue For and Exit For statements. VB

Dim numberSeq() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} For Each number As Integer In numberSeq ' If number is between 5 and 7, continue ' with the next iteration. If number >= 5 And number <= 8 Then Continue For End If ' Display the number. Debug.Write(number.ToString & " ") ' If number is 10, exit the loop. If number = 10 Then Exit For End If Next Debug.WriteLine("") ' Output: 1 2 3 4 9 10
You can put any number of Exit For statements in a For Each loop. When used within nested For Each loops, Exit For causes execution to exit the innermost loop and transfers control to the next higher level of nesting. Exit For is often used after an evaluation of some condition, for example, in an If...Then...Else structure. You might want to use Exit For for the following conditions: Continuing to iterate is unnecessary or impossible. This might be caused by an erroneous value or a termination request. An exception is caught in a Try...Catch...Finally. You might use Exit For at the end of the Finally block.

There an endless loop, which is a loop that could run a large or even infinite number of times. If you detect such a condition, you can use Exit For to escape the loop. For more information, see Do...Loop Statement (Visual Basic).

Iterators
You use an iterator to perform a custom iteration over a collection. An iterator can be a function or a Get accessor. It uses a Yield statement to return each element of the collection one at a time. You call an iterator by using a For Each...Next statement. Each iteration of the For Each loop calls the iterator. When a Yield statement is reached in the iterator, the expression in the Yield statement is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator is called. The following example uses an iterator function. The iterator function has a Yield statement that's inside a ForNext loop. In the ListEvenNumbers method, each iteration of the For Each statement body creates a call to the iterator function, which proceeds to the next Yield statement. VB

Public Sub ListEvenNumbers() For Each number As Integer In EvenSequence(5, 18) Debug.Write(number & " ") Next Debug.WriteLine("") ' Output: 6 8 10 12 14 16 18 End Sub Private Iterator Function EvenSequence( ByVal firstNumber As Integer, ByVal lastNumber As Integer) _ As System.Collections.Generic.IEnumerable(Of Integer) ' Yield even numbers in the range. For number = firstNumber To lastNumber If number Mod 2 = 0 Then Yield number End If Next End Function
For more information, see Iterators (C# and Visual Basic), Yield Statement (Visual Basic), and Iterator (Visual Basic).

Technical Implementation
When a For EachNext statement runs, Visual Basic evaluates the collection only one time, before the loop starts. If your statement block changes element or group, these changes don't affect the iteration of the loop. When all the elements in the collection have been successively assigned to element, the For Each loop stops and control passes to the statement following the Nextstatement. If element hasn't been declared outside this loop, you must declare it in the For Each statement. You can declare the type of element explicitly by using an As statement, or you can rely on type inference to assign the type. In either case, the scope of element is the body of the loop. However, you cannot declare element both outside and inside the loop. You can optionally specify element in the Next statement. This improves the readability of your program, especially if you have nested For Each loops. You must specify the same variable as the one that appears in the corresponding For Each statement. You might want to avoid changing the value of element inside a loop. Doing this can make it more difficult to read and debug your code. Changing the value of groupdoesn't affect the collection or its elements, which were determined when the loop was first entered.

When you're nesting loops, if a Next statement of an outer nesting level is encountered before the Next of an inner level, the compiler signals an error. However, the compiler can detect this overlapping error only if you specify element in every Next statement. If your code depends on traversing a collection in a particular order, a For Each...Next loop isn't the best choice, unless you know the characteristics of the enumerator object the collection exposes. The order of traversal isn't determined by Visual Basic, but by the MoveNext method of the enumerator object. Therefore, you might not be able to predict which element of the collection is the first to be returned in element, or which is the next to be returned after a given element. You might achieve more reliable results using a different loop structure, such as For...Next or Do...Loop. The data type of element must be such that the data type of the elements of group can be converted to it. The data type of group must be a reference type that refers to a collection or an array that's enumerable. Most commonly this means that group refers to an object that implements the IEnumerable interface of the System.Collections namespace or the IEnumerable<T> interface of the System.Collections.Generic namespace.System.Collections.IEnumerable defines the GetEnumerator method, which returns an enumerator object for the collection. The enumerator object implements theSystem.Collections.IEnumerator interface of the System.Collections namespace and exposes the Current property and the Reset and MoveNext methods. Visual Basic uses these to traverse the collection.

Narrowing Conversions
When Option Strict is set to On, narrowing conversions ordinarily cause compiler errors. In a For Each statement, however, conversions from the elements in group toelement are evaluated and performed at run time, and compiler errors caused by narrowing conversions are suppressed. In the following example, the assignment of m as the initial value for n doesn't compile when Option Strict is on because the conversion of a Long to an Integer is a narrowing conversion. In the For Each statement, however, no compiler error is reported, even though the assignment to number requires the same conversion fromLong to Integer. In the For Each statement that contains a large number, a run-time error occurs when ToInteger is applied to the large number. VB

Option Strict On Module Module1 Sub Main() ' The assignment of m to n causes a compiler error when ' Option Strict is on. Dim m As Long = 987 'Dim n As Integer = m ' The For Each loop requires the same conversion but ' causes no errors, even when Option Strict is on. For Each number As Integer In New Long() {45, 3, 987} Console.Write(number & " ") Next Console.WriteLine() ' Output: 45 3 987 ' Here a run-time error is raised because 9876543210 ' is too large for type Integer. 'For Each number As Integer In New Long() {45, 3, 9876543210} ' Console.Write(number & " ") 'Next Console.ReadKey() End Sub

End Module

IEnumerator Calls
When execution of a For Each...Next loop starts, Visual Basic verifies that group refers to a valid collection object. If not, it throws an exception. Otherwise, it calls theMoveNext method and the Current property of the enumerator object to return the first element. If MoveNext indicates that there is no next element, that is, if the collection is empty, the For Each loop stops and control passes to the statement following the Next statement. Otherwise, Visual Basic sets element to the first element and runs the statement block. Each time Visual Basic encounters the Next statement, it returns to the For Each statement. Again it calls MoveNext and Current to return the next element, and again it either runs the block or stops the loop depending on the result. This process continues until MoveNext indicates that there is no next element or an Exit For statement is encountered. Modifying the Collection. The enumerator object returned by GetEnumerator normally doesn't let you change the collection by adding, deleting, replacing, or reordering any elements. If you change the collection after you have initiated a For Each...Next loop, the enumerator object becomes invalid, and the next attempt to access an element causes an InvalidOperationException exception. However, this blocking of modification isn't determined by Visual Basic, but rather by the implementation of the IEnumerable interface. It is possible to implementIEnumerable in a way that allows for modification during iteration. If you are considering doing such dynamic modification, make sure that you understand the characteristics of the IEnumerable implementation on the collection you are using. Modifying Collection Elements. The Current property of the enumerator object is ReadOnly (Visual Basic), and it returns a local copy of each collection element. This means that you cannot modify the elements themselves in a For Each...Next loop. Any modification you make affects only the local copy from Current and isn't reflected back into the underlying collection. However, if an element is a reference type, you can modify the members of the instance to which it points. The following example modifies the BackColor member of each thisControl element. You cannot, however, modify thisControl itself. VB

Sub lightBlueBackground(ByVal thisForm As System.Windows.Forms.Form) For Each thisControl As System.Windows.Forms.Control In thisForm.Controls thisControl.BackColor = System.Drawing.Color.LightBlue Next thisControl End Sub
The previous example can modify the BackColor member of each thisControl element, although it cannot modify thisControl itself. Traversing Arrays. Because the Array class implements the IEnumerable interface, all arrays expose the GetEnumerator method. This means that you can iterate through an array with a For Each...Next loop. However, you can only read the array elements. You cannot change them.

Example
The following example lists all the folders in the C:\ directory by using the DirectoryInfo class. VB

Dim dInfo As New System.IO.DirectoryInfo("c:\") For Each dir As System.IO.DirectoryInfo In dInfo.GetDirectories() Debug.WriteLine(dir.Name) Next
The following example illustrates a procedure for sorting a collection. The example sorts instances of a Car class that are stored in a List<T>. The Car class implements theIComparable<T> interface, which requires that the CompareTo method be implemented. Each call to the CompareTo method makes a single comparison that's used for sorting. User-written code in the CompareTo method returns a value for each comparison of the current object with another object. The value returned is less than zero if the current object is less than the other object, greater than zero if the

current object is greater than the other object, and zero if they are equal. This enables you to define in code the criteria for greater than, less than, and equal. In the ListCars method, the cars.Sort() statement sorts the list. This call to the Sort method of the List<T> causes the CompareTo method to be called automatically for the Car objects in the List. VB

Public Sub ListCars() ' Create some new cars. Dim cars As New List(Of Car) From { New Car With {.Name = "car1", .Color = "blue", .Speed = 20}, New Car With {.Name = "car2", .Color = "red", .Speed = 50}, New Car With {.Name = "car3", .Color = "green", .Speed = 10}, New Car With {.Name = "car4", .Color = "blue", .Speed = 50}, New Car With {.Name = "car5", .Color = "blue", .Speed = 30}, New Car With {.Name = "car6", .Color = "red", .Speed = 60}, New Car With {.Name = "car7", .Color = "green", .Speed = 50} } ' Sort the cars by color alphabetically, and then by speed ' in descending order. cars.Sort() ' View all of the cars. For Each thisCar As Car In cars Debug.Write(thisCar.Color.PadRight(5) & " ") Debug.Write(thisCar.Speed.ToString & " ") Debug.Write(thisCar.Name) Debug.WriteLine("") Next ' Output: ' blue 50 car4 ' blue 30 car5 ' blue 20 car1 ' green 50 car7 ' green 10 car3 ' red 60 car6 ' red 50 car2 End Sub Public Class Car Implements IComparable(Of Car) Public Property Name As String Public Property Speed As Integer Public Property Color As String Public Function CompareTo(ByVal other As Car) As Integer _ Implements System.IComparable(Of Car).CompareTo ' A call to this method makes a single comparison that is ' used for sorting. ' Determine the relative order of the objects being compared. ' Sort by color alphabetically, and then by speed in ' descending order.

' Compare the colors. Dim compare As Integer compare = String.Compare(Me.Color, other.Color, True) ' If the colors are the same, compare the speeds. If compare = 0 Then compare = Me.Speed.CompareTo(other.Speed) ' Use descending order for speed. compare = -compare End If Return compare End Function End Class

For Loops
If you need to run the same statements repeatedly, you can program a loop. If you know how many times you want to loop, you can use a for loop. This kind of loop is especially useful for counting up or counting down:

Example
<html> <body> @For i=10 To 21 @<p>Line #@i</p> Next i </body> </html>

For Each Loops


If you work with a collection or an array, you often use a for each loop. A collection is a group of similar objects, and the for each loop lets you carry out a task on each item. The for each loop walks through a collection until it is finished. The example below walks through the ASP.NET Request.ServerVariables collection.

Example
<html> <body> <ul> @For Each x In Request.ServerVariables @<li>@x</li> Next x </ul> </body> </html>

While Loops
The while loop is a general purpose loop. A while loop begins with the while keyword, followed by parentheses, where you specify how long the loop continues, then a block to repeat. While loops typically add to, or subtract from, a variable used for counting. In the example below, the += operator adds 1 to the variable i, each time the loop runs.

Example
<html> <body> @Code Dim i=0 Do While i<5 i += 1 @<p>Line #@i</p> Loop End Code </body> </html>

Arrays
An array is useful when you want to store similar variables but don't want to create a separate variable for each of them:

Example
@Code Dim members As String()={"Jani","Hege","Kai","Jim"} i=Array.IndexOf(members,"Kai")+1 len=members.Length x=members(2-1) end Code <html> <body> <h3>Members</h3> @For Each person In members @<p>@person</p> Next person <p>The number of names in Members are @len</p> <p>The person at position 2 is @x</p> <p>Kai is now in position @i</p> </body> </html>
Do-Loops The most basic form of loop in Visual Basic is the Do-Loop. Its construct is very simple: Do

(Code to execute) Loop This, quite simply, executes the block of code, and when it reaches Loop, returns to the beginning of the Do Loop and executes the same block of code again. The same block of code will be repeatedly executed until it is told to stop executing. So let's try to apply this to our problem of generating the Fibonacci series: Dim X As Integer Dim Y As Integer Do Debug.Print X X=Y+X Y=X-Y Loop

And, believe it or not, this code works! Well, sorta. If you try to run this code, it will indeed generate the Fibonacci series; however, it will continually generate and print out the next number infinitely--or, in this case, until it reaches an overflow error. This is known as the problem of the infinite do-loop, one that all programmers will experience, and some quite frequently. Exit Do So we clearly need some way to escape from the Do-Loop. You could, of course, simply End the program once you have calculated enough values, but what if you still need to perform tasks after you're done calculating? The answer is to use the Exit Do statement. Whenever your program reaches an Exit Do statement within a loop, it will exit the current loop. So, let's try a somewhat different approach to the Fibonacci problem. We decide that we want to calculate only eight values of the Fibonacci series, so we'll keep a counter and increment it each time throughout the loop. Then, once the counter reaches eight, we'll exit the loop. Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. cnt = 1 Do Debug.Print X X=Y+X Y=X-Y If cnt >= 8 Then Exit Do

Else cnt = cnt + 1 End If Loop End Sub And now we're talking! This program successfully computes and prints out the first eight values of the Fibonacci series. Do Until As an alternative approach to nesting an If-Statement inside the loop, and invoking Exit Do once we're done looping, Visual Basic provides a Do Until statement. Its syntax is the following: Do Until (Expression) (Code to execute) Loop (Expression) can be any legal logical expression that we wish to evaluate to determine whether or not to exit the loop. Each time the program reaches Loop it will evaluate this expression. If the expression is True, it will exit the loop for us, but otherwise it will continue looping.. So let's try rewriting our Fibonacci program to use a Do-Until loop instead of Exit Do. Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. cnt = 1 Do Until cnt >= 8 Debug.Print X X=Y+X Y=X-Y cnt = cnt + 1 Loop End Sub Here we've replaced the hideous If cnt >= 8 Then ... Else: Exit Do with a very simple Until cnt >= 8. We must, however, still be sure to increment our counter every time through the loop, or else the Until expression will never be True, resulting in an infinite Do Loop. Do While In the place of Do Until, you can also use Do While. Its syntax is the following:

Do While (Expression) (Code to execute) Loop (Expression) can be any legal logical expression that we wish to evaluate to determine whether or not to exit the loop. Each time the program reaches Loop it will verify that this expression is True, and if it is False, it will exit the loop for us. Thus, instead of exiting when an expression is True, it now exits only once this expression is false. Let's try rewriting our Fibonacci program to use a Do-While loop instead of a Do-Until loop. Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. cnt = 1 Do While cnt < 8 Debug.Print X X=Y+X Y=X-Y cnt = cnt + 1 Loop End Sub For-Next Loops In situations where you merely want to run the loop a predefined number of times, it can become quite tiresome to have to create and manage a counter for each loop, which is why we also have something called a For-Next Loop. This kind of loop allows you to specify a counter, to tell it to count from one number to another each time through the loop, and to exit once the counter has reached its upper limit. The syntax is as follow: Dim I As Integer For I = (Integer) To (Integer) (Code to execute) Next I We used the variable name "I" above, as it is the most common name used for For-Loops; however, you can use any variable name you want, so long as the variable is of the type Integer. Now, let's improve our Fibonacci program even further: Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. For cnt = 1 To 8

Debug.Print X X=Y+X Y=X-Y Loop End Sub

Nesting Loops
You can nest For loops by putting one loop within another. The following example demonstrates nestedFor...Next structures that have different step values. The outer loop creates a string for every iteration of the loop. The inner loop decrements a loop counter variable for every iteration of the loop.
VB

For indexA = 1 To 3 ' Create a new StringBuilder, which is used ' to efficiently build strings. Dim sb As New System.Text.StringBuilder() ' Append to the StringBuilder every third number ' from 20 to 1 descending. For indexB = 20 To 1 Step -3 sb.Append(indexB.ToString) sb.Append(" ") Next indexB

Name: Jico Fernan C. Pangilinan Subject\Sec: COMP221-5x

Vous aimerez peut-être aussi