Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why curly braces for loop and if give wrong output in linear search in C?

When I used this function, it return -1 even if element of array was there.

int linear_search(int arr[], int length, int target)
{
   
    for (int i=0; i < n; i++) {
        if (arr[i] == target){
            return i;}
    
        return -1;
    }
}

I then removed curly braces and it worked

int linear_search(int arr[], int length, int target)
{
    for (int i=0; i < n; i++) 
        if (arr[i] == target) 
            return i;
    
        return -1;
    
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The first function would return -1 on the first iteration if arr[i] != target because a return statement follows the if statement inside the loop.

Aside: I couldn’t see the hidden braces at first. Consider adopting one of the following formatting styles:

#if 0
    for (int i=0; i < n; i++) {
        if (arr[i] == target){
            return i;}
#else
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i;
        }
    }

    // Or:
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == target)
        {
            return i;
        }
    }
#endif
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading