[Lesson 14] << [Contents] >> [Lesson 16]
15.1 Looping using For…Next Loop
The most common looping method in VB 2013 is the For….Next loop. The structure of a For…Next loop is as shown below:
For counter=startNumber to endNumber Step increment One or more statements Next
To exit a For…..Next Loop, you can place the Exit For statement within the loop; it is normally used together with the If….Then statement. For its application, you can refer to example 15.1 d.
Example 15.1 a
Dim counter as Integer For counter=1 to 10 ListBox1.Items.Add (counter) Next
* The program will enter number 1 to 10 into the list box.
Dim counter , sum As Integer For counter=1 to 100 step 10 sum+=counter ListBox1.Items.Add (sum) Next
* The programme will calculate the sum of the numbers as follows:
Dim counter, sum As Integer sum = 1000 For counter = 100 To 5 Step -5 sum – = counter ListBox1.Items.Add(sum) Next
*Notice that increment can be negative.
The program will compute the
subtraction as follow:
Dim n as Integer For n=1 to 10 If n>6 then Exit For End If Else ListBox1.Items.Add ( n) Next End If Next
The process will stop when n is greater than 6.
15.2 Looping using Do Loop
The Do Loop structures are
Do While condition Block of one or more statements Loop
Do Block of one or more statements Loop While condition
Do Until condition Block of one or more statements Loop
Do Block of one or more statements Loop Until condition
Sometimes we need exit to exit a loop prematurely because a certain
condition is fulfilled. The syntax to use is Exit Do. Let’s examine the following examples:
Do while counter <=1000 TextBox1.Text=counter counter +=1 Loop
* The above example will keep on adding until counter >1000.
The above example can be rewritten as
Do TextBox1.Text=counter counter+=1 Loop until counter>1000
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sum, n As Integer ListBox1.Items.Add(“n” & vbTab & “Sum”) ListBox1.Items.Add(“———————-”) Do n += 1 sum += n ListBox1.Items.Add(n & vbTab & sum) If n = 100 Then Exit Do End If Loop End Sub
* The loop in the above example can be replaced by the following loop:
Do Until n = 10 n += 1 sum += n ListBox1.Items.Add(n & vbTab & sum) Loop
The output is as shown in Figure 15.1
15.3 Looping using While….End While Loop
The structure of a While….End While Loop is very similar to the Do Loop. it takes the following form:
While conditions Visual Basic 2013 statements End While
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim sum, n As Integer ListBox1.Items.Add("n" & vbTab & "sum") ListBox1.Items.Add("———————-") While n <>10 n += 1 sum += n ListBox1.Items.Add(n & vbTab & sum) End While End Sub