Home > Software design >  How do I prevent an infinite loop when using an If statement inside of a Do loop?
How do I prevent an infinite loop when using an If statement inside of a Do loop?

Time:10-18

I'm trying to make a simple program that displays the output of a loop to the inside of a list box. The user would enter a number into a From text box. They would enter a number into a To text box. I need a conditional that only lets the program proceed if the From number is less than the To number. The program works until the From number is bigger than the To number, then it seems to be stuck in an infinite loop. The code looks like this:

    Dim intFrom As Integer
    Dim intTo As Integer
    Dim intNum As Integer = 1
    Integer.TryParse(txtFrom.Text, intFrom)
    Integer.TryParse(txtTo.Text, intTo)
    lstNumbers.Items.Clear()
    Do
        If intFrom < intTo Then
            lstNumbers.Items.Add(intNum)
            intNum  = 1
        End If
    Loop Until intNum > intTo

End Sub

CodePudding user response:

You can just skip the loop if your condition is false

    Dim intFrom As Integer
    Dim intTo As Integer
    Dim intNum As Integer = 1
    Integer.TryParse(txtFrom.Text, intFrom)
    Integer.TryParse(txtTo.Text, intTo)
    lstNumbers.Items.Clear()
    If intFrom < intTo Then
        Do
            lstNumbers.Items.Add(intNum)
            intNum  = 1
        Loop Until intNum > intTo
    End If

End Sub
  • Related