Search code examples
c#linear-search

Linear search in c#


Hey guys I am a beginner at coding and I'm doing a linear search in c# and can't figure out how to make it show in what array the number was found when doing the search. It just makes it say that it's on the last array. Here's my code:

Random Generator = new Random();
int[] array = new int[100];
int count = 0;
for (int i = 0; i < array.Length; i++)
{
    array[i] = Generator.Next(1, 100);
    count++;
}
Console.WriteLine("Write a number between 1-100 and see if it's in a array and in what array.");
int guess = Convert.ToInt32(Console.ReadLine());

bool exists = array.Contains(guess);
if (exists)
{
    Console.WriteLine("Your number {0} is in the {1}th Array.", guess, count);
}
else
{
    Console.WriteLine("Your number {0} does not match any number in any of the Arrays.", guess);
}

Console.ReadKey();

There's something wrong with my count int, but I don't know what to do. Thanks in advance.


Solution

  • I think you are looking for Array.IndexOf

    Int index = Array.IndexOf(amountOfArrays,guess);
    If (index == -1)
    {
        // not found
    }
    else 
    {
        // found
    }
    

    Count++ will be the last. How would you expect it to be anything else?