Thread: 1-D array question

1. 1-D array question

hey guys , i was wondering if u could tell me a few ways to find if a certain element(no,char,or whatever) exists in an array or not.
ex: i enter 10 elements in an array through a for loop then how do i check if an element is found in the array or not ?

2. If you know what you are looking for before entering the elements in the array you don't even need to do another iteration. Just test if the element you are inserting is the one you are looking for and then set a flag variable.

3. any other ways than using a flag variable ?

4. There is a lot of research done on searching algorithms (Search algorithm - Wikipedia, the free encyclopedia), but many of them require your data to be sorted to work efficiently (Sorting algorithm - Wikipedia, the free encyclopedia). I strongly suggest that you peruse the above articles just for your edification, but given that you seem to have a small array, I would just do a simple linear search.

Simply iterate through your array, and compare each element against your search term. A common return value for an array search function is the index of the item if found, or -1 if not found. Here is some pseudo-code:
Code:
```// look for item in array, returning the index if found, or -1
int search(item, array, array_length)
for i from 0 to array_length {
if array[i] equals item
return i
}
return -1```

5. mm thanks for the help

6. Originally Posted by everyone0
any other ways than using a flag variable ?
Well, unless there is some pattern to the data that you know of in advance searching through an unsorted array is pretty much going to be O(n).

If the data was sorted, you could use a divide and conquer algorithm for less comparisons.

Popular pages Recent additions