/* testarr13.cpp CIS 150 06/19/2008 David Klick This program demonstrates how to search for information in parallel arrays. */ #include #include using std::cin; using std::cout; using std::setw; using std::left; void cont(); int find(int id[], int length, int idnum); int main() { int n, pos; const int ARRAY_SIZE = 4; // declare and initialize arrays of names // fname array stores first names // lname array stores last names // id array stores id numbers // These are parallel arrays because the elements // with the same index in each array are related. char fnames[][15] = { "Bob", "Carol", "Ted", "Alice" }; char lnames[][12] = { "Hope", "O'Connor", "Danson", "Springs" }; int id[ARRAY_SIZE] = { 99, 27, 32, 18 }; // loop until user chooses to exit do { // find out which ID # the user wants to display cout << "Find which user id? (-999 to exit) "; cin >> n; // display desired name if user didn't choose to exit if (n != -999) { pos = find(id, ARRAY_SIZE, n); if (pos == -1) { cout << "Error: ID number not found\n"; } else { // display names associated with ID # cout << left << setw(10) << lnames[pos] << fnames[pos] << '\n'; } } } while (n != -999); cont(); return 0; } /* int find(int id[], int length, int idnum); Arguments: int id[]: holds employee ID numbers int length: number of elements in id[] array int idnum: employee number to search for Returns: an integer indicating the position in the id[] array where idnum was found, or -1 if idnum was not found Searches for an ID number within an array of ID numbers and returns the position where found, or -1 if not found. */ int find(int id[], int length, int idnum) { int i; for (i=0; isungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); } /* Sample output: Find which user id? (-999 to exit) 1 Error: ID number not found Find which user id? (-999 to exit) 18 Springs Alice Find which user id? (-999 to exit) 99 Hope Bob Find which user id? (-999 to exit) 27 O'Connor Carol Find which user id? (-999 to exit) 32 Danson Ted Find which user id? (-999 to exit) -999 */