Sunday, 6 May 2012

Sequential Search in C


#include <cstdlib>
#include <ctime>
#include <iostream>
int main()
  {
  int item;
  int found;
  const int MAX = 5;
  int arr[MAX+1];
  srand((unsigned)time(0));
  arr[1] = (rand()%10)+1;
  cout << arr[1] << "  ";


  for(int i=2; i<MAX+1; i++)
    {
    arr[i] = arr[i-1] + (rand()%10)+1;
    cout << arr[i] << "  ";
    }
  cout << "\n";
  cout << "Which number do you want to find: ";
  cin >> item;


  found = 0;
  for(int j=1; j<=MAX; j++)
    {
     if (found == 0)
     {
       cout << "Checking array location " << j << "\n";
      if (arr[j] == item)
      {
      found = 1;                              
 }
      }
   }
  cout << "\n";


  if (found == 1)
    {
     cout << "Found it!";
   }
  else
    {
      cout << "The number you want is not in the list.";
   }
   cout << "\nPress ENTER to continue..." << endl;
   getchar();
  }

No comments:

Post a Comment