0

I had got some good advice previously but need just a little more help as really struggling. How do I test my linear search algorithm?

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


/**
 * Returns true if value is in array of n values, else false.
 */
int main (void)
{
    int value = 3;
    int values[] = {2,3,4};
    int n = 3;

    bool search;
    printf("% bool\n");




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


}

1 Answer 1

0

You cannot define a function within another. You could do it like

#include <stdio.h>

// declare search, so you can use it
bool search(int value, int values[], int n);

int main (void)
{
    int value = 3;
    int values[] = {2,3,4};
    int n = 3;

    printf("%s\n", search(value, values, n) ? "Found!" : "Not found!");
}


// define search
/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    if (n> 0)
    {
        for (int i = 0; i < n ; i++)
        {
            if (values[i]==value)
            {
                return true;
            }
        }
        return false;
    }
    return false;
}

(I added some braces and indentation to the for loop, so it's obvious what is part of it, at least I got confused)

You don't need that first return false;, if you remove it, the second one will be executed immediately at the same point. You don't even need if (n>0), as in the for loop, i is set to 0 and tested for i < n.

1
  • thank you so much Commented Jul 27, 2017 at 18:26

You must log in to answer this question.

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