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.
The FOR NEXT Loop , execute the loop body (the source code within For ..Next code block) to a fixed number of times.
- 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.
- 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
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.
When you execute the above source code , the program shows the message box only three times .