For Loop in VB.net
By: Ramlak Printer Friendly Format
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. |
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures in VB.net
Passing a Variable Number of Arguments to Procedures in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Using Resume Next and Resume Line in VB.net
Using On Error GoTo 0 in VB.net
Archived Comments
1. wehhh... so so so difficult
View Tutorial By: sam at 2013-02-28 01:55:41