1

I feel like I am close, but not sure why my haystack values are not printing.

I am trying to write linear search code for the search() function in helpers.c, and this is what seems to me to be the right logic (although it must be wrong) for the search boolean:

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

However, when I run ./generate 10 1 | ./find 9158 in the Terminal, the printout is missing a value for all the haystack values and it returns false, since the printout says Didn't find needle in haystack. I ran ./generate 10 1 separately, so I could see what number is guaranteed to be in there and 9158 was there.

Any ideas why the haystack doesn't print and it doesn't recognize the 9150 needle?

1

Consider what would happen the first time the loop executes. For example, if the first item in the list is not the number you are looking for, then when the code reaches the 'if' condition, the condition will evaluate to false, and the function will return right there and then without comparing the remaining values.

The code should only return true if a match is found, but continue looping if no match is found.

If the loop completes and no match was found after inspecting all values, only then should the function return false.

| improve this answer | |
  • Thanks Luke, you're right, if it doesn't find it in the first loop, it would give a false reading. Thanks! I now put the return false; outside of the loop, and it works. :) Although I still see a blank printed out with the haystack iterations. Is that supposed to have numbers in it? E.g. haystack[0] = some number. – Azurespot Aug 21 '14 at 18:47
  • I get the same output haystack[0] = , with no trailing number. At the end it displays "Found needle in haystack!", and the pset was accepted by check50. So it would seem that is the expected behaviour. – Luke Van In Aug 21 '14 at 19:14
  • Ah okay, thanks! – Azurespot Aug 22 '14 at 6:30

You must log in to answer this question.

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