// Faan Tone Liu, winter 2003 // linear search function, and testing it #include #include using namespace std; int linearSearch(const int b[], int size, int searchkey); // read elements of an array in from a file. Sort them. // Get search key from user, search for it in array. int main() { const int maxarrlen(100); const int maxnamelen(80); char filename[maxnamelen]; ifstream listfile; int arr[maxarrlen]; int numelements(0); int key, result; cout << "Enter file name containing list (no more than 100 elements): "; cin >> filename; listfile.open(filename, ios::in); // open input file if (!listfile.is_open()) { cout << "Unable to open file." << endl; return 1; } // read the list from the file into the array while (listfile >> arr[numelements]) numelements = numelements + 1; cout << "What number are you looking for? "; cin >> key; result = linearSearch(arr, numelements, key); if (result < 0) cout << "The number was not found in the list" << endl; else cout << "The number " << key << " was found at position " << result << " of the array." << endl; return 0; } //Search through array b which contains size elements to locate the // index of searchkey, a value we hope to find in b. If it is // not found, return -1 int linearSearch(const int b[], int size, int searchkey) { int i; for (i=0; i < searchkey; i++) if (searchkey == b[i]) return i; return -1; }