bool method and out parameter

4.7k Views Asked by At

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

2

There are 2 best solutions below

1
Eric On BEST ANSWER

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.

1
morsecodist On

One simple way you could do this is make your method similar to Java's indexOf (docs). Instead of returning a boolean from your method you could return the count and return -1 if the item isn't found. Like this:

//in the Search class
public int LinearSearchEx (int target, int[] array)
{    
    for (int i = 0; i < array.Length; i++)
    {

        if (target == array[i])
        {
            return i + 1;
        }
    }
    return -1;
}

Then use it:

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);

int outNum = s.LinearSearchEx(value, numsarr)
if(outNum > 0)
{
    Console.WriteLine("Found it");
    Console.WriteLine("Out num is {0}", outNum);
}
else
{
    Console.WriteLine("Sorry not found");
    // Note that outnum will always be the array length if the number wasn't found
    Console.WriteLine("Out num is {0}", numsarr.Length);

}