Search code examples
vbagoto

How to use Do While Loop / While End While Loop in this code instead of GoTo


I'm a bit new with Visual Basic and I'm trying to make a program that would generate random numbers from 1 to 9 without repetition using arrays. I've also read that instead of using GoTo statements (as they are generally frowned upon), Do While Loop or While End While Statements could be used. I've tried using these loops but have not made it work. Here is the code:

Dim x As Integer = 0, y As Integer = 0, num As Integer = 0, arr(8) As Integer
        lstLoop.Items.Clear()
        For x = 0 To 8 
Start:
            Randomize()
            num = Fix(Rnd() * 9) + 1
            For y = 0 To 8
                If num = arr(y) Then
                    GoTo Start
                End If
            Next
        arr(x) = num
        lstLoop.Items.Add(arr(x))
        Next

Solution

  • The idea is to loop while you have found the number in the array:

    Sub GenerateRandom()
    
    Dim x As Integer
    Dim num As Integer
    Dim arr(8) As Integer
    
    Randomize Timer
    
    For x = 0 To 8
        Do
            num = Fix(Rnd() * 9) + 1
        Loop While FindInArray(arr, x - 1, num)
    
        arr(x) = num
    Next x
    
    End Sub
    
    Function FindInArray(arr() As Integer, maxIndex As Integer, num As Integer) As Boolean
    
    Dim i As Integer
    FindInArray = False
    
    For i = 0 To maxIndex
        If arr(i) = num Then
            FindInArray = True
            Exit Function
        End If
    Next
    
    End Function