Search code examples
c#incrementlinear-searchout-parameters

bool method and out parameter


So I have this code

//in the Search class
public bool LinearSearchEx (int target, int[] array, out int number)
{
    number = 0;

    for (int i = 0; i < array.Length; i++)
    {

        if (target == array[i])
        {
            number += 1;
            return true;

        }
    }
    return false;
}

What I want to do is have the method increment the number parameter each time it checks if the number is found in the array, This is how I called it in main.

Search s = new Search();
int num = 0;
int [] numsarr = new int[10] { 5, 4, 3, 6, 7, 2, 13, 34, 56, 23 };
int value = 6;
Console.WriteLine("num is {0}", num);
if(s.LinearSearchEx(value, numsarr, out num) == true)
{
    Console.WriteLine("Found it");
    Console.WriteLine("Out num is {0}", num);
}
else
{
    Console.WriteLine("Sorry not found");
    Console.WriteLine("Out num is {0}", num);

}

I am not sure where to increment the out number in my method cause the way I have it now only increments 1 and nothing more. If the value is not found it should print out the length of the whole array. Do increment in two places in my array? Thank you, quite new to coding


Solution

  • You are only incrementing your out 'number' when the item is found. So 'number' is always either 0 or 1 for you. It sounds like you want 'number' to represent the place in your array where it was found. Like this:

    public bool LinearSearchEx (int target, int[] array, out int number)
    {
        number = 0;
    
        for (int i = 0; i < array.Length; i++)
        {
            number = i + 1;
            if (target == array[i])
            {
                return true;
    
            }
        }
        return false;
    }
    

    The above will return the length of the array if it isn't found. If it is found it will return the place in the array.