0

I am a beginner wanted to get started on pset 3. After watching all the videos i started to implement search as follow :

bool search(int value, int values[], int n)
{
  int b = 0;
  for (b=0;b<n; b++)
  {
    if (value==values[b])
      {
      return true; 
      }
    else
      {
      return false;
      }
  }

I looked up the error and if i understand it correctly.. my function does not always return a boolean value.

I just dont understand why that is.

1
  • If you consider that any of the posts answers your question, you should mark it as accepted.
    – wallek876
    Feb 3 '15 at 20:58
1

You don't need:

else
{

    return false;

}

If we have return true the loop will end, so just put a return false at the very end of the function.

0
0

At every possible iteration of your for loop(actually the first one), the value is compared with the element stored at ith index of array values. So for the first comparison i.e. values[0], the condition is checked whether value == values[0] which will return either true or false and the obtained is immediately returned. Hence, the function only compares the first element of the values[] with value, and then quits, which is undesirable. You probably need to do something like this.

bool found = 0; // by default assume that the value isn't present in values[]
for (b = 0 ; b < n ; ++b)
{
     if (value == values[b])
     {
          found = 1; //set found to 1, indicating that we got the value in the array
          break;
     }
}
if (found == 0)
    return false;
else
    return true;
0

Because you asked for why:

The compiler is complaining that you only return a value if the for loop executes. The for loop doesn't execute if n <= 0. Now you may know that you will never give it a value where n < 0 so for practical purposes it works for you, but the compiler still raises this as a concern.

To solve this error you need to return a value after the loop is complete, this guarantees that the function will always return a value regardless of the value of n.

You must log in to answer this question.

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