0
bool search(int value, int values[], int n)
{
    int p;

    if(n<=0)
    {
     return 1;
    }

    for(p=0;p==n;p++)
    {
    if(values[p]==value)
    {
        return 0;
        break;
    }
    }
    return 1;
    }
2

There are two issues to address here.

The expected return value of this function is a bool, but you are returning an int. Now, it is the case that you can use 1 and 0 as true and false, respectively. However, 0 means false and 1 means true. As a result, the return values are actually opposite what you probably intend them to be.

Consider the structure of your for loop. The general formula is this:

for (initialization; condition; update)

Your condition is p==n. Since the code in the loop only executes until the condition is false, your program can never enter into the loop to examine each value in values[]; it fails its first test. Thus, every time your program runs, it returns 1, which is equivalent to returning true.

3
  • Thanks for the answer Peter. I'm a real beginner. I changed the code accordingly as you suggested, and now the bool always returns false. Even if the value is in the array of values. Is it because of the return false; I included after the for loop?
    – Vaish MK
    Jan 21 '17 at 12:56
  • No, you need that return false. I just ran your code through check50, and it passed. Maybe there's another issue elsewhere? A couple other notes...you don't need "break" after "return true." The return statement will end execution of search if it is reached, so break will never be reached. You can delete it. Also, your condition should be "p < n." You will not want to access values[5] if there are are 5 values. The indexes will run 0...4, so indexing to 5 should be avoided.
    – Peter
    Jan 21 '17 at 18:37
  • Thanks! I had a slight problem working with boolean functions (esp the return commands) And yeah the problem was elsewhere, the sort function above it. Thanks again.
    – Vaish MK
    Jan 22 '17 at 6:35

You must log in to answer this question.

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