Net-informations.com
SiteMap  | About    

How to use FOR NEXT loop in vb.net

Whenever you face a situation in programming to repeat a task for several times (more than one times ) or you have to repeat a task till you reach a condtition, in these situations you can use loop statements to achieve your desired results. This kind of for loop is useful for iterating over arrays and for other applications in which you know in advance how many times you want the loop to iterate.

for-next-loop

The FOR NEXT Loop , execute the loop body (the source code within For ..Next code block) to a fixed number of times.

  
For var=[startValue] To [endValue] [Step]
   [loopBody]
Next [var]

var : The counter for the loop to repeat the steps.

starValue : The starting value assign to counter variable .

endValue : When the counter variable reach end value the Loop will stop .

loopBody : The source code between loop body

Lets take a simple real time example , If you want to show a messagebox 5 times and each time you want to see how many times the message box shows.

  
1.	startVal=1
2.	endVal = 5
3.	For var = startVal To endVal
4.	    show message
5.	Next var

Line 1: Loop starts value from 1

Line 2: Loop will end when it reach 5

Line 3: Assign the starting value to var and inform to stop when the var reach endVal

Line 4: Execute the loop body

Line 5: Taking next step , if the counter not reach the endVal

VB.NET Source Code

  
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object,
	ByVal e As System.EventArgs) Handles Button1.Click
        Dim var As Integer
        Dim startVal As Integer
        Dim endVal As Integer
        startVal = 1
        endVal = 5
        For var = startVal To endVal
            MsgBox("Message Box Shows " &   var &   " Times ")
        Next var
    End Sub

End Class

When you execute this program , It will show messagebox five time and each time it shows the counter value.

If you want to Exit from FOR NEXT Loop even before completing the loop Visual Basic.NET provides a keyword Exit to use within the loop body.

  
For var=startValue To endValue [Step]
   [loopBody]
   Contition
   [Exit For]
Next [var]




Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, 
	ByVal e As System.EventArgs) Handles Button1.Click
        Dim var As Integer
        Dim startVal As Integer
        Dim endVal As Integer
        startVal = 1
        endVal = 5
        For var = startVal To endVal
            MsgBox("Message Box Shows "  var   " Times ")
            If var = 3 Then
                Exit For
            End If
        Next var
    End Sub
End Class

When you execute the above source code , the program shows the message box only three times .


 VB.NET Program Flow Control - Related Contents


 VB.NET Program Flow Control - Related Programs