Visual Basic (2008 Express)
Linear Search

Example in VB : An array of 10 exam marks is to be searched to find the one mark that was greater than 90...The mark is then displayed in a TextBox called txtResult

First the array has to be declared and values assigned to each element of the array....

 

Dim Mark(9) As Integer

Mark(0) = 65
Mark(1) = 48
Mark(2) = 78
Mark(3) = 60
Mark(4) = 39
Mark(5) = 71
Mark(6) = 93
Mark(7) = 55
Mark(8) = 62
Mark(9) = 51

 

Remember the maximum subscript is 9, which means there are 10 elements in the array.
There are two ways of carrying out a linear search...

Method 1 : involves using an integer variable (n) that counts the element being checked. The value of this counter needs to be incremented after each check...

 

Dim n As Integer

n = 0

Do

    If Mark(n) > 90 Then
        txtResult.Text = Mark(n)
    End If

    n = n + 1

Loop Until Mark(n - 1) > 90

 

 
 
Method 2 : Use a For...Next Loop...

 

Dim n As Integer

For n = 0 To 9

    If Mark(n) > 90 Then
        txtResult.Text = Mark(n)
   
End If

Next

 

n is the Control Variable for the loop. It must be declared as an integer...and basically counts from 0 to 9 for each time the loop is executed.

   Back