0

Why wouldn't you put a corresponding else statement within the for loop? The return false at the bottom corresponds to the for loop, but nothing corresponds to the if statement (it doesn't work when I add the else)

bool search(int value, int values[], int n)
{   
    for (int i = 0; i<=n; i++)
    {   
        if(value==values[i])
        { 
            return true;
        }
        //why no else (return false) statement here too?
    }
    return false;
}
1
  • a return statement terminates the execution of a function. if you have an else statement here that returns false if value is not equal to values[i], the will only loop iterate once, checking only the first element in the array, and if value is there, the function will return true, otherwise, the function will return false. I don't think that's what you want.
    – kzidane
    Jun 3 '15 at 19:38
1

The for loop is testing each character in the string array values[], one at a time. If it finds a match to the character stored in value, it will return true. When it does execute the return, it will immediately leave the loop and the function, and go back to the code that called the search() function.

On the other hand, if there is no match, the for loop will complete. That means that the character stored in value was not found in the character array values[]. Now, you want to tell the calling code that it wasn't found. This is done with return false;.

Finally, what about putting an else clause on the if statement inside the loop. What would the code do? If the test was true, then it would execute the return true; statement. However, if the first character in the array did not match the character stored in value, then the else statement would immediately execute return false; and return to the calling code. The rest of the characters in the array would never be tested.

In short, you want to test each character in the array and only exit with the return true; statement when the first match is found. If no match is found, and only after testing every character in the array (the for loop is finished), at that point, you want to return false;.

If this answers your question, please accept the answer so that the question is removed from the unanswered question pool. Let's keep up on forum housekeeping. ;-)

You must log in to answer this question.

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