0

I wanted to find consecutive and non-consecutive numbers separated by hyphens. Once i ran this given code it gave me an error as "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'". What is wrong with this code, please explain if anyone knows..

    public static void Main(string[] args)
    {
        Console.Write("Enter a few numbers (eg 1-2-3-4): ");

        var input = Console.ReadLine();
        var numArray = new List<int>();

        foreach (var number in input.Split('-'))
        {
            numArray.Add(Convert.ToInt32(number));
        }
        numArray.Sort();

        var isConsecutive = true;
        for (int i = 0; i < numArray.Count; i++)
        {
            if (numArray[i] != numArray[i + 1] - 1)
            {
                isConsecutive = false;
                break;
            }
        }

        if (isConsecutive)
        {
            Console.WriteLine("Consecutive");
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("Not Consecutive");
            Console.ReadLine();
        }
    }
  • In which line you have the exception? – Ygalbel Jun 03 '20 at 08:31
  • Welcome to Stack Overflow. You've used the `compiler-errors` tag, but if this is an exception then it's *not* a compiler error. The bug is quite simple - you're using `numArray[i + 1]` even when `numArray` is `numArray.Count - 1`, but it's really important to understand the different between compile-time errors and exceptions. – Jon Skeet Jun 03 '20 at 08:31

1 Answers1

4

The problem is :

numArray[i + 1]

when your i reaches the last index, there is no item left at i+1 which ends up in index out of range exception.

You need to rethink about the logic if you really need i + 1 and safe guard so that you don't access the index that does not exists actually.

probably you want :

for (int i = 0; i < numArray.Count - 1; i++)

so that it stops at the second last item of the array.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160