-3

I'm learning control flow and trying to write code for grab 5 different numbers, store then into an array, sort and print. Im getting exception saying the array is out of bounds, but i can't see why, since im storing 5 objects into a [4] array.

Any tips why im getting this exception?

    public static void Three()
    {
        var numbers = new int[4];
        var i = 0;
        while (i <= 4)
        {
            Console.WriteLine("enter a number: ");
            var input = Convert.ToInt32(Console.ReadLine());
            if (Array.IndexOf(numbers, input) != -1)
            {
                Console.WriteLine("try again");
            }
            else
            {
                numbers[i] = input;
                i++;
            }
        }
        Array.Sort(numbers);
        foreach (var item in numbers)
        {
            Console.WriteLine(Convert.ToString(item));
        }
    }
niceguy335
  • 361
  • 1
  • 3
  • 7
  • "5 objects into a [4] array" - you may want to re-read that part of your question... As good practice searching for language + exception name (i.e. https://www.bing.com/search?q=C%23%20IndexOutOfRangeException in this case) is good first step *before* asking a question. – Alexei Levenkov Sep 10 '16 at 03:11

1 Answers1

1

but i can't see why, since im storing 5 objects into a [4] array.

Because a [4] array hold 4 objects at the indexes 0, 1, 2, and 3. If you want to hold 5 objects you need a int[5] and use indexes 0-4. This is why you usually see i < 4 and not i <= 4 like you have.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431