Search the location of key in the list, -1 is returned if the value is not found - C++ Data Structure

C++ examples for Data Structure:Search

Description

Search the location of key in the list, -1 is returned if the value is not found

Demo Code

#include <iostream>
using namespace std;
int linearSearch(int [], int, int);  //function prototype
int main()// www  . jav  a  2 s . c o  m
{
   const int NUMEL = 10;
   int nums[NUMEL] = {5,10,22,32,4,6,3,8,9,11};
   int item, location;
   cout << "Enter the item you are searching for: ";
   cin  >> item;
   location = linearSearch(nums, NUMEL, item);
   if (location > -1)
      cout << "The item was found at index location " << location
   << endl;
   else
      cout << "The item was not found in the list\n";
   return 0;
}
int linearSearch(int list[], int size, int key)
{
      int i;
      for (i = 0; i < size; i++)
      {
         if (list[i] == key)
            return i;
      }
      return -1;
}

Result


Related Tutorials