// add grave accents before and after code
// to show it nicely in your question.
bool search(int value, int values[], int n)
{
if(n<0)
{
return false;
}
// TODO: implement a searching algorithm
for(int i=0;i<n;i++)
{
if(values[i]==value)
{
goto LABEL1;
}
else
{
goto LABEL2;
}
}
LABEL1:return true;
LABEL2:return false;
}
1 Answer
When you return
in a C program, your function stops. This will happen even in the middle of a loop.
You are evaluating the first element. If it is the one you wanted, you are returning true
. Else (if it is not the value you wanted), you are returning false. Since you returned, you end the function and you never evaluated the second element nor the rest of them.
I suggest you take out of the loop this piece of your code:
else
{
goto LABEL2;
}
And instead just add this line before you end your function:
goto LABEL2;
Probably a good place to place it is after the curly brace that closes the loop and before the label definitions.
That way you only return false
if you went through the whole array and you never found the value you wanted (you never returned true
).