Zebra0.com

visual-basic loops

Notice that the test value of 1000 is never hit exactly. When the while loop is executed, the Boolean expression is tested: if it is true the body of the loop is executed. When it gets to the Wend statement it goes back to the top and tests again. The loop is repeated until the test fails, then the next statement after the End While is executed. A While loop can execute zero or more times.

After the value 512 is added to the list box, num is assigned a new value of 1024. When the control goes to the while statement, the expression Num<1000 is false and the loop ends. When the loop ends the next statement after the End While is executed.

Note: If the Boolean expression is true, all of the statements in the loop execute, even if the expression becomes false during the loop. Look at the difference in the output when the position of the increment is changed: Everything is exactly the same except for the increment:

'Programmer: Janet Joy
'While loop generates 2,4,8,...1024
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim Num As Integer
        ListBox1.Items.Add("Powers of 2")
        Num = 1
        While Num < 1000
            Num = Num * 2
            ListBox1.Items.Add(Num)
        End While
    End Sub
End Class

NEXT: For Loops