15. Most useful loop structures.
There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times.
VB.Net provides following types of loops to handle looping requirements:-
- For Next loop
The For Next loop executes the statements from an initial value to the uper limit value. You can use the Step keyword to specify the updating step of the loop.
For counter [ As datatype ] = start To end [ Step step ]
- [ statements ]
- [ Continue For ]
- [ statements ]
- [ Exit For ]
- [ statements ]
Next [ counter ]
- For Each loop
For Each loop is used to loop through a collection of items (e.g. list). Its general form is shown below.
For Each element [ As datatype ] In group
- [ statements ]
- [ Continue For ]
- [ statements ]
- [ Exit For ]
- [ statements ]
Next [ element ]
- While The while loop continuously executes statements as the condition is true. You must provide end point for the loop, otherwise the statements will executed infinitely.
While condition
- [ statements ]
- [ Continue While ]
- [ statements ]
- [ Exit While ]
- [ statements ]
End While Note: Exit statement is used to exit a loop
- Do While It repeats the enclosed block of statements while a Boolean condition is True or until the condition becomes True. It could be terminated at any time with the Exit Do statement.
Do { While | Until } condition
- [ statements ]
- [ Continue Do ]
- [ statements ]
- [ Exit Do ]
- [ statements ]
Loop -or-
Do
- [ statements ]
- [ Continue Do ]
- [ statements ]
- [ Exit Do ]
- [ statements ]
Loop { While | Until } condition |
- *With End It is not exactly a looping construct. It executes a series of statements that repeatedly refers to a single object or structure. The syntax for this loop construct is −
With object
- [ statements ]
End With