0

This is my linear search code. How do I test it to see if it works?

 /**
 * 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.
 */

bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm

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

Inside the main function, make an array, aka int values[]. Then call the bool function and pass in arguments: any integer i.e int value, the array values[], then the size i.e n.

But your function probably won't work because it goes through the loop only once and if the first member of values[] is not your value then it will return false. Place the return false; outside the for loop, when i has iterated through the array and your value still hasn't been found.

1
  • Thank you for your help. Really struggling, would be grateful for more help if possible. Please see my code below – stephen Ong Mar 20 '17 at 21:08
0

You cannot call search by itself. Instead, you'd call find (build it first with make find) with a number (./find 4711), and provide an input array where that number appears in some place (test at least for first index, last index, and somewhere around the middle), or is absent. Use Ctrl+D to end number input if you're doing it manually.

You could hard-code your own test suite by adding a main function to helpers.c, and call search on that one, but that would mean you'd have to re-compile for new tests.

Hint on your specific code: Your code will never test the second element of the values array, since you always return after testing the first.

4
  • thank you for your help. Really struggling to test this code. Can you help further? – stephen Ong Mar 20 '17 at 21:05
  • #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; } } } – stephen Ong Mar 20 '17 at 21:14
  • Do not return false within the loop, that's what I meant with the "hint". The way you wrote it, you only ever look at the first element. – Blauelf Mar 21 '17 at 7:15
  • Thank you so much for your help. I understand now. Thanks ! – stephen Ong Mar 22 '17 at 21:10

You must log in to answer this question.

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