-1

I tried making find and then running ./generate 1000 50 | ./find 127 but it won't find the needle in the haystack. This is what I have for helpers.c:

#include "cs50.h"

#include "helpers.h"

bool search(int value, int values[], int n)
{
    for (int i = 0; i < n; i++)

    {
        if (values[i] == value)
          return true;
        else
          return false;
    }
    return false;
}
4

This is a common mistake. What your code does is simply checking whether the first element of the array is equal to the value. What you wish is to iterate over the whole array. But after checking the first element of the array, you simply give it a choice to return false if the the element you were searching for is not found. Instead, you should do something like this.

bool found = false;
for (int i = 0 ; i < n ; ++i)
{
     if (values[i] == value)
     {
         found = true;
         break;
     }
}
return found;

The fact to be considered here is that the value you are searching for may reside not necessarily on the first element(0th index) of array.

I have put the break statement as it is useless to search for the value in the rest of the array once it has been found, so that doesn't make a difference as you shall be returning true at last. Here, break optimizes this code, but not changes the time complexity.

Hope that helps.

| improve this answer | |
  • Ah okay the problem is there can only be one return value so I can't just tell it to return true or false for every iteration. Thanks! – Evan Mar 9 '16 at 19:48

You must log in to answer this question.

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