0

So I was trying to figure out what the code for the linear search function should be and I can't understand where the "false" output should be implemented.

The code:

bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm
    if(n <= 0)
    {
        return false;
    }

    for(int i = 0; i < n; i++)
    {
        if(i == value)
        {
            return true;
        }
    }
}

If I try to use an else function after the if one the program doesn't want to compile but if I put the return false at the end, it returns false every time (obviously). So, I hope any of you guys gives me a tip on how to build this function and where to put the 'return false' so that those problems don't appear.

1

if you have code like:

if(...)
    return true
.....
else(...)
    return false

this is an error, the compiler needs to know what value is to be returned, but if you have a condition if-else like the above, the compiler "can not know" a priori, what value will really return, your program linear search neither is correct, you should not look for the index but the value corresponding to that index:

if (values [i] == value)

return false must be at the end of main (without conditions if or else)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .