For...Next Loops


In this lesson, I'll take you through the For Loop structure with a couple of simple code examples. Undoubtedly the For...Next loop structure is the most useful among others.
  
Example: To print 0 to 10.
Dim i As Integer
For i = 0 To 10
    Print i
Next i

When the value of i is 0, the Print statement is executed then i is incremented to 1. It checks whether the value of i is from 0 to 10. If it satisfies, the Print statement is executed again. In this way, the loop goes on until the value of i exceeds 10. Every time, the value of i is incremented by 1.



Example: To print 0 to 6 in steps of 2.
Dim i As Integer
For i = 0 To 6 Step 2
    Print i
Next i

Every time, the value of i is incremented by 2.


Output:
0
2
4



Example: To print in descending order from 10 to 0 in step of -3.
Dim i As Integer
For i = 10 To 0 Step -3
    Print i
Next i

Every time, the value of i is decremented by 3.


Output:
10
7
4
1



Exit For and Exit Do statement  

A For Next Loop can be terminated by an Exit For statement and a Do loop can be terminated by an Exit Do statement.

Example: Exit For statement :
Dim i As Integer
For i = 0 To 10
    If i = 3 Then
    Exit For
    End If
Print i
Next i

Output:
0
1
2



Example: Exit Do statement
Dim num As Integer
num = 0
Do While num < 10
    Print num
    num = num + 1

    If num = 4 Then
        Exit Do
    End If

Loop

Output:
0
1
2
3