# Thread: Using Linear Search to find multiple indexes

1. Member
Join Date
Mar 2011
Posts
2
Rep Power
0

## Using Linear Search to find multiple indexes

Okay first of all, yes this is homework which I have been asked to complete. Help which I am asking for with this is to simply point me in the right direction.

What I have asked to do is to use linear search to find a value in an array (let's say for example that the number was 6) and then to find all of the indexes in which 6 appears in the array.

int[] a = [3, 2, 6, 1, 0, 0, 6]

so the result which I should receive should be 2 and 6 as those are the positions in which 6 appears. (Also need a return value if it isn't in the list but I can do that.)

My logic is to run a for loop in the method that is responsible for searching the array and to print it. This does work but my issue here now is that -1 (this is the flag that says that the value is not present in the array) is always returned to the main method which means that as far as the program is concerned, every time the program is executed, there are never any indexes found from the search.

Example of what is printed on screen:

[3, 2, 6, 1, 0, 0, 6]
enter a value to search:> 6
2 6 The specific value which you have searched for is not present in this array.

I hope I have been clear and thank you for your time.

2. Java Code:
```//define list to search
int[] a = {3, 2, 6, 1, 0, 0, 6};
//define number to find in list
int searchTerm = 6;
//define a List because we don't know how many answers there will be so we can't use an Array
//for each integer item in the array "a"; int i=a
for (int i:a) {
//if i=6, add to our List
}
//print our list using the Java Formatter
System.out.printf("We found %d at location %d%n",searchTerm,i);
}```
In case you are unfamiliar with "printf", the first %d is replaced by searchTerm, and the second %d is replaced by i, and %n makes a line break like "println" does.
Last edited by ozzyman; 03-16-2011 at 05:39 PM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•