Searching an Array

//  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;

//  read numbers into the array
   index = fillArray(nums);

//  get numbers to search for and print a message telling whether each
//  number was found
   cout << endl << "Value to search for (-999 to end): ";
   cin >> number;
   while (number != SENTINEL)
   {
      if (search(nums,index,number))
         cout << "The number was found in the array" << 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; return the number of values read and
//  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 true if value is
//  found, otherwise return false
int search(int list[],int length, int value)
{
   bool found = 0;
   int i = 0;
   while (i < length && !found)
   {
      if (list[i] == value)
         found = 1;
      i++;
   }
   return found;
}

Sample Execution

Enter a number (-999 to end): 42
Enter a number (-999 to end): 10
Enter a number (-999 to end): 5
Enter a number (-999 to end): 39
Enter a number (-999 to end): 6
Enter a number (-999 to end): 13
Enter a number (-999 to end): -999

Value to search for (-999 to end): 5
The number was found in the array
Enter a number (-999 to end): 88
The number was not found in the array
Enter a number (-999 to end): 42
The number was found in the array
Enter a number (-999 to end): 0
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