Steve G Steve G - 1 month ago 7
C++ Question

C++ Sequential search not finding the last element

So I have an input file. It consists of 40 numbers. The first 20 numbers are input into an array (I've checked this, they're actually there). I then close and re-open the input file. I compare the first 20 numbers in the input file against my array using sequential search. This means they should all be successful. I then compare the next 20 numbers against the numbers in my array, they should all be unsuccessful searches. My array is unsorted at this point.

The problem I'm running into is that the last number for successful is never found using sequential. I'm not sure how to fix this.

Here is the sequential search function:

length = 19;

void Search::sequential(ItemType item, bool& found)
{
int place = 0;
while (place < length && item != list[place])
place++;
found = (place < length);
}


And here is my successful/unsuccessful loops

outFile << "\n\n ************Sequential Successful ********** \n";
outFile << endl << "ID" << endl;

inFile >> num;
for(int i=0; i<=length && inFile; i++)
{
search.sequential(num, found);
if (found)
outFile << num << endl;

inFile >> num;
}


//sequential unsuccessful
outFile << "\n\n ************Sequential unsuccessful ********** \n";
outFile << endl << "ID" << endl;

for(int i=0; i<=length && inFile; i++)
{
search.sequential(num, found);
if (!found)
outFile << num << endl;

inFile >> num;
}


However, my output is:

************Sequential Successful **********

ID
1111
3352
4567
5678
6789
7890
8901
9012
1223
2113
8546
2374
4723
9573
3284
7474
8594
3589
5858
//THERE SHOULD BE 1925 HERE BUT THERE ISN'T

************Sequential unsuccessful **********

ID
9456
3584
2222
4319
4477
5710
5497
1502
1599
1504
1506
9943
8833
9944
6678
5555
5660
9911
6130
1613


If I remove the "if (found)" statement everything works perfectly, but how do I get around this without removing that?

Thanks in advance

---------------edit---------------

Okay, when I changed length to 20 it still didn't seem to work. I'm so lost.

Here is where I create the array

inFile >> num;
for (int i=0; i<length && inFile; i++)
{
search.addToList(num);
inFile >> num;
}


and here is the addToList function

void Search::addToList(ItemType num)
{
if (index < length) //ive tried taking out this statement just to see if it makes a difference and it didn't
{
list[index] = num;
index++;
}
}


I initialize index to 0 in the constructor

This is how I declare the array

ItemType list[length];


IT WORKS!!!! Thank you all SO much! I really appreciate it so much.

Answer

There are 2 solutions : length should get 20 as value

length = 20;

or use "<=" instead of "<" (in this case "length" should be named "lastIndex")

void Search::sequential(ItemType item, bool& found) 
{  
  int index = 0; 
  while (index <= length && item != list[index]) 
    index++; 
  found = (index <= length);  
}