Searches array for a value. - C++ Data Type

C++ examples for Data Type:Array

Description

Searches array for a value.

Demo Code

#include <iostream>
using namespace std;
const int MAX = 100;
void fill_parts(long int parts[MAX]);
void main()//from   w  w  w . j  a v  a2s  . co  m
{
   long int search_part;            // Holds user request.
   long int parts[MAX];
   int ctr;
   int num_parts=5;          // Beginning inventory count.
   fill_parts(parts);    // Fills the first five elements.
   do
   {
      cout << "\n\nPlease type a part number...";
      cout << "(-9999 ends program) ";
      cin >> search_part;
      if (search_part == -9999)
      {
         break;
      }             // Exits loop if user wants.
      // Scans array to see whether part is in inventory.
      for (ctr=0; ctr<num_parts; ctr++) // Checks each item.
      {
         if (search_part == parts[ctr])       // If it is in inventory...
         {
            cout << "\nPart " << search_part << " is already in inventory";
            break;
         }
         else
         {
            if (ctr == (num_parts-1) )      // If not there, adds it.
            {
               parts[num_parts] = search_part;   // Adds to end of array.
               num_parts++;
               cout << search_part << " was added to inventory\n";
               break;
            }
         }
      }
   } while (search_part != -9999);     // Loops until user signals end.
   return;
}
void fill_parts(long int parts[MAX])
{
   // Assigns five part numbers to array for testing.
   parts[0] = 12345;
   parts[1] = 24724;
   parts[2] = 54154;
   parts[3] = 73496;
   parts[4] = 83925;
   return;
}

Result


Related Tutorials