/********************************************/
// R. A. Hillyard
// search.cpp
// March 2001
//
// program does a linear search of an array
// and returns the location (index) if in the list.
/********************************************/
#include <iostream.h>
int search(int a[], int arraySize, int keyValue);
int main()
{
int a[10] = {2, 4, 6, 8, 1, 3, 5, 7, 9, -33};
int index;
int key;
while(true)
{
cout<<"Enter one of the following keys: 1, 2, 3, 4, 5, 6, 7, 8, 9, -33\n";
cout<<"to find its location in the array.>";
cin>>key;
index = search(a, 10, key);
if(index >= 0)
cout<<"\nthe key is at location "<<index<<endl;
else
{
cout<<"\nthe key is not in the list \n";
break;
}
}
return 0;
}
//*******************************************************************/
//search for a given key
//*******************************************************************/
int search(int t[], int size, int key)
{
int i = 0;
while(i < size)
{
if(t[i] == key)
return i;
i++;
}
return -1;
}
//*******************************************************************/
/****************************Program Output***********************************/
Enter one of the following keys: 1, 2, 3, 4, 5, 6, 7, 8, 9, -33
to find its location in the array. (any other key to quit) >2
the key is at location 0
Enter one of the following keys: 1, 2, 3, 4, 5, 6, 7, 8, 9, -33
to find its location in the array. (any other key to quit) >4
the key is at location 1
Enter one of the following keys: 1, 2, 3, 4, 5, 6, 7, 8, 9, -33
to find its location in the array. (any other key to quit) >6
the key is at location 2
Enter one of the following keys: 1, 2, 3, 4, 5, 6, 7, 8, 9, -33
to find its location in the array. (any other key to quit) >9
the key is at location 8
Enter one of the following keys: 1, 2, 3, 4, 5, 6, 7, 8, 9, -33
to find its location in the array. (any other key to quit) >-33
the key is at location 9
Enter one of the following keys: 1, 2, 3, 4, 5, 6, 7, 8, 9, -33
to find its location in the array. (any other key to quit) >0
the key is not in the list