Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I use FindIndex() it returns -1 in c#?

I’m trying to build a simple program that sorts numbers from biggest to smallest with arrays in c#.

//basic number sorter. every number should be on one line and separated by a " " (space).
int[] numbers = Console.ReadLine().Split(" ").Select(int.Parse).ToArray();
int[] bigToSmall = new int[numbers.Length];
int biggestNum = int.MinValue;
for (int y = 0; y < numbers.Length; y++)
{
    for (int i = 0; i < numbers.Length; i++)
    {
        if (numbers[i] > biggestNum)
        {
            biggestNum = numbers[i];
        }
        else if (numbers[i] == biggestNum)
        {
            numbers[i] = biggestNum;
        }
    }
    var bigIndx = Array.FindIndex(numbers, row => row == biggestNum);
    numbers[bigIndx] = 0;
    bigToSmall[y] = biggestNum;
}
for (int i = 0; i < bigToSmall.Length; i++)
{
    Console.WriteLine(bigToSmall[i]);
}

When I run the program I get: "Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array."

Here are also the values I get when I use the input "1 2 3"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried to use also IndexOf,but it didnt work. Any ideas why it doesn’t work, and how I can fix it?

>Solution :

It will be the second iteration through the y loop. You haven’t reset biggestNum back to minvalue so it will be looking for the one you removed last time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading