// read numbers into an array, then prompt the user for values and // search the array to see if the given values are in the array #include <iostream.h> const int SENTINEL = -999; const int SIZE = 10; int search(int list[],int length, int value); int fillArray(int nums[]); int main() { int nums[SIZE]; int index; int number; int loc; index = fillArray(nums); cout << endl << endl; cout << "Value to search for (-999 to end): "; cin >> number; while (number != SENTINEL) { loc = search(nums,index,number); if (loc != -1) cout << "The number was found in position " << loc << endl; else cout << "The number was not found in the array" << endl; cout << "Enter a number (-999 to end): "; cin >> number; } return 0; } // read numbers into the array passed to this function and return // the number of values stored in the array int fillArray(int nums[]) { int index; index = 0; cout << "Enter a number (-999 to end): "; cin >> nums[0]; while (nums[index] != SENTINEL && index < SIZE) { index++; cout << "Enter a number (-999 to end): "; cin >> nums[index]; } return index; } // search the array list for the value given, assuming that length // positions of the array have been filled; return the subscript // where the value was found or -1 if not found int search(int list[],int length, int value) { int location = -1; int i = 0; while (i < length && location == -1) { if (list[i] == value) location = i; i++; } return location; }
Enter a number (-999 to end): 77 Enter a number (-999 to end): 44 Enter a number (-999 to end): 88 Enter a number (-999 to end): 22 Enter a number (-999 to end): 3 Enter a number (-999 to end): -999 Value to search for (-999 to end): 55 The number was not found in the array Enter a number (-999 to end): 22 The number was found in position 3 Enter a number (-999 to end): 77 The number was found in position 0 Enter a number (-999 to end): 4 The number was not found in the array Enter a number (-999 to end): -999
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2002