Search code examples
ccs50

What is the difference between if and else if


#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>

int binary(int a[],int target,int l,int r); //return index , needs array, target  left index, right index
//goal: find if the number is in the array
int main(void)
{
    int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13};
    int target = get_int("number:");
    int l = 0;
    int r = 13;
    int index=binary(a,target,l,r);
    if(index>=0)
        printf("number %i is at index %i\n",target,index);
    else
        printf("not found\n");
}
int binary(int a[],int target,int l,int r)
{
    if(r<l)
    {
        return -1;
    }
    int mid=l+(r-l)/2;

    if(a[mid]==target)
    {
        return mid;
    }

    if(a[mid]<target)
    {
        return binary(a,target,mid+1,r);
    }
    if(a[mid]>target)
    {
        return binary(a,target,l,mid-1);
    }
}

Error when I compile this:

non-void function does not return a value in all control paths
[-Werror,-Wreturn-type]

However, I do not understand why I get this error message even though all my if statements have a return value.

However, when compared to the answer key, they used else if. I understand why they are right, but I do not understand why I am wrong though.


Solution

  • The issue lies in your recursive calls to the binary function. Let's take a closer look:

    if(a[mid]<target)
    {
        return binary(a,target,l+1,r); // This should be mid+1 instead of l+1
    }
    if(a[mid]>target)
    {
        return binary(a,target,l,r-1); // This should be mid-1 instead of r-1
    }
    

    In the recursive calls, you're not adjusting the boundaries properly. When you're searching the left half of the array, you should update r to mid - 1, not r - 1. Similarly, when searching the right half, you should update l to mid + 1, not l + 1.

    Here's the corrected code:

    if(a[mid]<target)
    {
        return binary(a,target,mid+1,r);
    }
    if(a[mid]>target)
    {
        return binary(a,target,l,mid-1);
    }