VB.Net: Do Loops and For…Next Loops
Do loops are important programming structures as they permit a series of statements to be repeated until a condition is met. Do loops are to be used when the number of loops to be made is undetermined. For…Next loops are to be used when the number of loops to be made is known. With For loops, the counter is incremented within the For statement whereas with the Do loop, the loop is incremented within the series of statements.
There are pre-test and post-test do loops. Post-test loops are preferred if you’d like the loop to execute once before meeting the condition, such as for input verification. Pre-test loops, like For loops, only execute if the initial condition is met.
Here’s a code snippet of a pre-test do loop…
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim counter As Integer
counter = 1
While counter <= 5 ’
ListBox1.Items.Add("Iteration: " & counter)
counter += 1
End While
End Sub
End Class
Notice that the test comes before the loop executes...
Here’s a code snippet of a post-test do loop…
Public Class Form1
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim counter As Integer
counter = 1
Do
ListBox2.Items.Add("Iteration: " & counter)
counter += 1
Loop Until counter <= 5
End Sub
End Class
Notice that the test comes after the first loop…
Pretest Do loops are most appropriate for when the number of iterations to be made is not known. A For…Next loop is the preferred repetitive structure if you want to execute a series of statements a given number of times. For example, if you want to repeat a series of statements 8 times, a For…Next loop is the most practical choice. A Do Loop may be used however, but the same scenario can be programmed more efficiently with a For…Next loop.
The following code snippet demonstrates the structure for the For…Next Loop for VB.Net. ..
Public Class Form1
'Clicking the button will output each iteration with its corresponding iteration number
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
For i = 1 To 5
ListBox1.Items.Add("Iteration: " & i)
Next
End Sub
End Class
You can see that the while loop requires one more line of code to increment the counter. As a general rule, you should use a For loop when you know exactly how many times a loop should execute as it increases readability.
newarrival4u 3 months ago
nice post