Ben Donnelly
Ben Donnelly

Reputation: 1261

Search for number in an array

I'm having some trouble with the exercise I got given from my teacher.

Exercise: Write a program to input 5 numbers. Ask the user to a input a number for searching the array. The program should search for this number and tell the user if it has been found in the array or not. For example, if it has been found then the position of the array which the number occupies should be display. For example "Your number is 6. It has been fond in the position 3 of the list."

Obviously, I can just use a for loop and get 5 numbers and put them into the array. But Im not sure how to check if then the number the user wants to search for is in the array.

Heres my attempt http://pastebin.com/t2DcdSvU Im not sure how to put it into code tags :S

Upvotes: 0

Views: 123

Answers (2)

Andrew Backes
Andrew Backes

Reputation: 1904

First, obtain you user input. So let's say you have your array, and a target value. For the example, let's just say your user input created the following:

Dim numbers = {1, 2, 9, 6, 4}
Dim target = 2

Now all you need to do is loop through the array, and compare the target, to the current value of the array.

For x = 0 To 4
    If target = numbers(x) Then
        MsgBox "Your number is " + target ", found at position " + x
        Exit For
    End If
Next x

Upvotes: 1

Ryan J
Ryan J

Reputation: 8323

You can use that same concept to search the array.

Assuming you won't have a sorted array, you can simply use a for loop to check each value of the array and compare with the entered value to search.

Use a for loop or whatever construct you want to populate the array, then use another to loop through the array and for each value, do a compare and determine if the user entered a number that's in the array.

If you get a match, print out the resulting index number and return.

Here's a sample of code that will do what you need:

Dim value As Integer
value = 0
' This loop goes from 0 to 4.
For index As Integer = 0 To 4
    value = myArray(index)
    ' Exit condition if the value is the user number.
    If (value = usernum) Then
       Console.writeline("Your number was " & usernum & " found at: " & index & "\n")
       Exit For
    End If
Next

Upvotes: 0

Related Questions