Find first element in an array

mary13

Newcomer
Joined
Nov 18, 2003
Messages
3
Location
Australia, from Minnesota
I am using an array to go through a file containing the numbers, 3, 77, 0, 29, 28 and I want to find the index FIRST multiple of 7, but my code finds all the mulitples of seven and outputs the index of 28 instead of 77.

Here is the coding I have so far:


Dim target() As Double
Dim upperbound As Integer

Form Load
Dim sr As IO.StreamReader = IO.File.OpenText("multiples.txt")
Dim change As Double
Dim i As Integer

upperbound = 0
Do While (sr.Peek <> -1)
change = sr.ReadLine
upperbound += 1
Loop
sr.Close()

ReDim target(upperbound)
sr = IO.File.OpenText("multiples.txt")
For i = 0 To upperbound - 1
target(i) = sr.ReadLine
Next
sr.Close()
End Sub

Private Sub btnDisplay_Click
Dim maxindx As Integer
lstBox.Items.Clear()
lstBox.Items.Add(find(maxindx))
End Sub

Function find(ByVal maxindx As Double) As Double
Dim i As Integer
Dim found As Double

maxindx = 0
For i = 0 To upperbound - 1
If target(i) Mod 7 = 0 Then
found = target(i)
maxindx = i
End If
Next i
Return maxindx

End Function

Thanks for helping!
 
the for ... next loop will keep looping till all items in the array have been checked - you will need to either count backwards through the items or exit the loop when a match is found
Visual Basic:
For i = 0 To upperbound - 1
    If target(i) Mod 7 = 0 Then
        found = target(i)
        maxindx = i
        Exit For     'This should exit the loop after a match
    End If
Next i
 
Back
Top