You will be given two input files, CLSStandard.txt and CLSTest.txt . The CLSStan
ID: 3540533 • Letter: Y
Question
You will be given two input files,
CLSStandard.txt and CLSTest.txt. The CLSStandard.txt file contains integer values against
which we are searching. (There will be no more than 100 of these.) The CLSTest.txt file
contains a set of numbers that we are trying to locate within the standard data set. (There will be
no more than 50 of these.) Read both of these into separate arrays and then determine which of
the numbers in the LSTest file are included in the LSStandard data set by using a Linear Search
algorithm. Have your program print out a report (to the console only is sufficient) that indicates
whether the number was found or not.
Your output should look something like:
Number 1 (34) was located in position 15.
Number 2 (74) was not in the file.
Number 3 (56) was not in the file.
Number 4 (103) was located in position 75.
etc.
Notes:
Your function header for the Linear Search function should look like:
int searchList(int stdList [], int numElems, int value)
Explanation / Answer
// assumes CLSStandard.txt and CLSTest.txt are located in the same directory from where you run this code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int searchList(int stdList [], int numElems, int value)
{
int res=-1;
for(int i=0;i<numElems;i++)
{
if(stdList[i]==value)
{
res=i;
break;
}
}
return (res+1);
}
int main () {
int elems[100];
int vals[50];
int numElems =0;
int numVals =0;
ifstream myfile("CLSStandard.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
myfile>>elems[numElems];
numElems++;
}
}
myfile.close();
myfile.open("CLSTest.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
myfile>>vals[numVals];
numVals++;
}
}
myfile.close();
int pos;
//display output
for(int i=0;i<numVals;i++)
{
if( pos = searchList(elems, numElems, vals[i]) )
cout<<"Number "<<(i+1)<<" ("<<vals[i]<<") was located in position "<<pos<<"."<<endl;
else
cout<<"Number "<<(i+1)<<" ("<<vals[i]<<") was not in the file."<<endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.