Searching Through an Unsorted List of Integers (slightly differently)

list - the list to be searched
item - the item we're looking for
length - the number of elements in the list
index - the location of the item (if found)

Returns: TRUE if the item was found, FALSE if the item was not found.
Boolean Search(const int list[],
               int item,
               int length,
               int& index)
{
  index = 0;
  while (index < length && item != list[index])
    index++;

  return (index < length);
}
Now, you would use the function in this way:
int index;

Boolean found = Search(list, 14, 15, index);

if (found)
  cout << "14 was found at index: " << index;
else
  cout << "14 was not found";
Previous page
Next page

Back to Lesson 2 Index
Back to Outline