' Visual Basic 2008 9.0 .NET Examples - Searching through Arrays - Linear Search - Arrays : Module LinearSearch Sub Main() Dim base As Integer = 2 Dim count As Integer = 10 Dim upperbound As Integer = count - 1 Dim numbers(upperbound) As Integer ' Dim index As Integer For index = 0 To upperbound numbers(index) = (index + 1) * base Next ' Dim number As Integer For number = base - 1 To base * count + 1 ' linear search Dim found As Boolean = False Dim exhausted As Boolean = False index = -1 Do Until found OrElse exhausted index += 1 found = (numbers(index) = number) exhausted = (index = upperbound) Loop ' output If found Then Console.Write(number & " found at index " & index) Else Console.Write(number & " not found") End If If exhausted Then Console.WriteLine(", search exhausted") Else Console.WriteLine(", search not exhausted") End If Next ' Console.ReadLine() End Sub End Module Module ExerciseTask Sub Main() Dim count As Integer = 3 Dim names() As String = {"Brussels", "Antwerp", "Ghent"} Dim zipCodes() As Integer = {1000, 2000, 9000} ' Console.WriteLine("Zip Code ?") Dim zipCode As String = Console.ReadLine() ' ' ... (linear search) ... ' Console.ReadLine() End Sub End Module Module ExerciseSolution Sub Main() Dim count As Integer = 3 Dim names() As String = {"Brussels", "Antwerp", "Ghent"} Dim zipCodes() As Integer = {1000, 2000, 9000} ' Console.WriteLine("Zip Code ?") Dim zipCode As String = Console.ReadLine() ' Dim found, exhausted As Boolean Dim index As Integer = -1 Do Until found OrElse exhausted index += 1 found = (zipCodes(index) = zipCode) exhausted = (index = count - 1) Loop ' If found Then Console.WriteLine(names(index)) Else Console.WriteLine("City not found.") End If ' Console.ReadLine() End Sub End Module Module IndexOf Sub Main() Dim base As Integer = 2 Dim count As Integer = 10 Dim upperbound As Integer = count - 1 Dim numbers(upperbound) As Integer ' Dim index As Integer For index = 0 To upperbound numbers(index) = (index + 1) * base Next ' Dim number As Integer For number = base - 1 To base * count + 1 index = Array.IndexOf(numbers, number) ' (1) Dim found As Boolean = index > -1 ' output If found Then Console.WriteLine(number & " found at index " & index) Else Console.WriteLine(number & " not found") End If Next ' Console.ReadLine() End Sub End Module ' Visit www.studyvb.com for more examples. Copyright 2003-2008 De Wolf.