For Loop in VB.net
By Ramlak Viewed: 31946 times Emailed: 220 times Printed: 200 times
The For loop is probably the most popular of all Visual Basic loops. The Do loop doesn't need aloop index, but the For loop does; a loop index counts the number of loop iterations as the loop executes. Here's the syntax for the For loop—note that you can terminate a For loop at any time with Exit For:
For index = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [index]
The index variable is originally set to start automatically when the loop begins. Each time through the loop, index is incremented by step (step is set to a default of 1 if you don't specify a value) and when index equals end, the loop ends.
Here's how to put this loop to work; in this case, I'm displaying "Hello from Visual Basic" four times (that is, intLoopIndex will hold 0 the first time; 1, the next; followed by 2; and then 3, at which point the loop terminates):
Module Module1
Sub Main()
Dim intLoopIndex As Integer
For intLoopIndex = 0 To 3
System.Console.WriteLine("Hello from Visual Basic")
Next intLoopIndex
End Sub
End Module
Here's what you see when you run this code:
Hello from Visual Basic Hello from Visual Basic Hello from Visual Basic Hello from Visual Basic Press any key to continue
If I were to use a step size of 2:
For intLoopIndex = 0 To 3 Step 2
System.Console.WriteLine("Hello from Visual Basic")
Next intLoopIndex
I'd see this result:
Hello from Visual Basic Hello from Visual Basic Press any key to continue
| Tip |
Although it's been common practice to use a loop index after a loop completes (to see how many loop iterations were executed), that practice is now discouraged by people who make it their business to write about good and bad programming practices. |
Comments(0)
Be the first one to add a comment
Latest Tutorials
| [2009-03-22] | Handling Timer Events - and Creating an Alarm Clock in VB.net |
| [2009-03-22] | Creating Menus in Code using VB.net |
| [2009-03-22] | Creating Context Menus in Code using VB.net |
| [2009-03-22] | Creating Tree Views in Code using VB.net |
| [2009-03-22] | Creating List Views in Code using VB.net |
| [2009-03-16] | Send SMS using VB code |
| [2009-02-27] | Creating a Windows Service in VB.net |
| [2009-02-27] | Creating a Windows Service Installer in VB.net |
| [2009-02-24] | OleDbConnection class in VB.net |
| [2009-02-24] | OleDbDataAdapter class in VB.net |
| [2009-02-24] | DataSet Class in VB.net |
| [2009-02-24] | DataTable Class in VB.net |
| [2009-02-24] | DataRow Class in VB.net |
| [2009-02-22] | Chat Server in VB.net |
| [2009-02-22] | A tutorial on Chat Server and Chat Client in VB.net |
Most Viewed Articles (in last 30 days)

