In my code, after successfully searching the element, the function is returning true and false both to the main function. I have questions as follows ->

1 - Why the sm() function is returning true then false and how can I stop the function just after the value is searched ?

2 - Why I have to use break to end this while loop ?

#include <stdio.h>
#include <cs50.h>

bool search (int value, int values[], int n);
bool sm(int value, int values[], int l, int h);

int main(void)
    int values[100], value, n;
    printf("How many values you want to enter:\n");
    n = GetInt();
    printf("Enter the values:\n");
    for (int i = 0; i < n; i++)
        values[i] = GetInt();
    printf("What do you wanna search:\n");
    value = GetInt();
    search (value, values, n);

bool search(int v, int va[], int n)
    int l, h;
    l = 0;
    h = n-1;
    bool result = sm (v, va, l, h);
    return result;

bool sm(int value, int values[], int l, int h)
    int mid = (l + h) / 2;
    if(value == values[mid])
        return true;
    while (l<h)
        if (value > values[mid])
            sm(value, values, mid+1, h);
        else if(value < values[mid])
            sm(value, values, l, mid-1);
    return false;

The sm() function recursively calls itself, but fails to recursively return the result. For a detailed discussion, check out Pset3 Binary Search problems

The break in this while loop forces the loop to terminate after only one pass, when the break is encountered. It will never make a second pass. It appears to be necessary because l and h never change within the while loop during any recursion. If the while loop get's started (and has no break), it will never stop unless and until the test condition goes false. Remember that with recursive calls of a function, each recursion level has it's own set of variables, independent of every other recursion.

Finally, I'm wondering if this your code above is a practice program before you actually do the assignment. It looks like you've written your own find.c file from scratch. The instructions at http://cdn.cs50.net/2016/x/psets/3/pset3/pset3.html#search imply what used to be stated outright - you need to change the functions in the helpers.c file, but find.c should not be changed at all. This is also implied in the command for check50. It uploads helpers.c, but not find.c.

There may be other problems within your code, but this should get you started.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |

You must log in to answer this question.

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