0
votes

I realised that when I included the "else return false" in my bool search, it will never be able to "find the needle". Conversely, if I were to remove that part, the program works fine. It is able to find 2008 and not find 2013. Any idea why is this so?

 /**
 * helpers.c
 *
 * Computer Science 50
 * Problem Set 3
 *
 * Helper functions for Problem Set 3.
 */

#include <cs50.h>

#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */

 //value = needle , values[] = haystack, n = size
bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm
    if(n<0)    
    return false;


    for(int i=0;i<n;i++)
    {
        if(value == values[i]) 
        {           
            return true;
        }

        else
        {
            return false;
        }


    }
    return false;
}

/**
 * Sorts array of n values.
 */
void sort(int values[], int n)
{
    // TODO: implement an O(n^2) sorting algorithm
    return;
}
2

2 Answers

2
votes

Look at the code carefully:

for(int i=0;i<n;i++)
{
    if(value == values[i]) 
    {           
        return true;
    }

    else
    {
        return false;
    }


}

The loop body always returns from the function - thus it will only run once (assuming n > 0). This is the same as testing whether value is in the first position of the haystack.

If you take out the else branch, the code in the loop body only returns when the value is found. If it's not found, it will check the next element, and the next, etc., until either you find it or you run out of elements.

0
votes

I think you should implement sort function first . the search will not work without sort . if you try the above code with needle say 1 and you but 1 in the beginning if haystack it will return true . but if you put 1 in the second of the haystack it will return false even you are looking for 1 .