Thompson Thompson - 17 days ago 5
C++ Question

Returns false everytime

I made a simple sequential search function, so as i'm testing it, if I put 25 into my search item it returns true, but the other numbers 90, 21 are always false and I cant for the life of me understand why its doing that. Any help would be much appreciated.

int a[] = {25,90,21};
int searchItem = 90;

if(sequentialSearch(searchItem, a, 3) == 1)
{
cout << "Found Item" << endl;
}
else
{
cout << "Item Not Found" << endl;
}

bool sequentialSearch(int searchItem, int * a, int size)
{
for(int i = 0; i < size; i++)
{
if(searchItem == a[i])
{
return true;
}
else
{
return false;
}
}
}

Answer

you return false if your element is not at first position. Try this

bool sequentialSearch(int searchItem, int * a, int size)
{
    for(int i = 0; i < size; i++)
    {
        if(searchItem == a[i])
        {
            return true;
        }
    }
    return false;
}
Comments