4/26/11

[VB.NET][TUT] FOR | NEXT | loop

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.

FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic.NET 2005 ( VB.NET 2005) .

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

Example:


 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]  

No comments: