Loops in Visual Basic

A common mistake with loops is to omit the first value and include an extra value past the intended end point.

'Programmer: Janet Joy
'An endless While loop
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
        End While
    End Sub
End Class

Occasionally, you create a loop that will never end. In the example above, if you comment out the statement Num=Num*2, Num starts out as 1 and stays 1. The statement Num<1000 will always be true. Depending on what else the loop is doing, the system may eventually give you an error message, or you will realize the program is “frozen” or “hung-up.” If you are working in VB, you can click the dark red square on the toolbar or select Debug,Stop Debugging from the menu to end the program.

NEXT: Do Loops