// Mr. Minich
// CMPSC 101
// Ch. 5 Demo Program #8
// January 30, 2000
// Purpose - a sequential (aka linear) search
#include <iostream>
#include <fstream>
using namespace std;
int loadNumbers(int numbers[100]);
void sequentialSearch(int numbers[100], int searchNum);
int main()
{
int numbers[100]; // numbers to search through
int searchNum = 0; // number to search for
if(loadNumbers(numbers)) // Load array with numbers from data file.
{
cout << "Enter the number for which you want to search: ";
cin >> searchNum;
sequentialSearch(numbers, searchNum);
}
else
{
cout << "An error occurred while opening the file.\n";
}
return 0;
}
// Function to load the array with numbers from a data file.
bool loadNumbers(int numbers[100])
{
int index = 0; // position within array
bool status = false; // flag variable for status of opening file
ifstream infile("NUMBERS.TXT"); // file to be read
if (infile) // If no error occurred while opening file input the data from the file.
{
for(index = 0; index <= 99; index++)
{
infile >> numbers[index];
}
infile.close();
status = true;
}
return status;
}// end of loadNumbers
void sequentialSearch(int numbers[100], int searchNum)
{
int index = 0; // position within array
while((index < 100) && (search_num != numbers[index]))
{
// Loop while the number is not found & while more elements remain.
if(numbers[index] != searchNum)
{ // If current element is not the one for which we are
index++; // searching, increment subscript index.
}
}
if(index < 100) // If loop ended before index reached 100, then the
{ // number was found.
cout << "A sequential search found the number in " << index + 1 << " comparisons.\n";
}
else
{
cout << "Number was not found by sequential search after " << index << " comparisons." << endl;
}
}// end of sequentialSearch