0

So basically what I need to do is create an array, have the user populate the array, then I just bubble sort the array. I have the basic idea of the stuff i'm trying to write the issue is I keep running the program then once I enter the 10 values I get the error message " Index outside bounds of Array". I've played around with the code a bit and can't seem to crack the issue. I'm still new to this so please be patient with me.

class Program
{
    public static void Main(string[] args)
    {
        Console.Write("\n\n");
        Console.Write("Input 10 or less values then hit enter to sort values");
        Console.Write("\n\n");

        int[] Arr = new int[10];

        for ( int i = 0; i <= 10; i++)
        {
            Console.Write("Input Value\n");
            Arr[i] = int.Parse(Console.ReadLine());


        }

        for (int i = 0; i <= 10; i++)
        {
            for (int j = Arr.Length - 1; j > i; j--)
            {
                if (Arr[j] < Arr[j - 1])
                {
                    var temp = Arr[j];
                    Arr[j] = Arr[j - 1];
                    Arr[j - 1] = temp;
                }
            }
        }

        foreach (int i in Arr)
        {
            Console.WriteLine(i);
        }

        Console.Read();



    }
}

}

  • 1
    Debug please. Index out of bounds is pretty descriptive, the ans is in the code you posted – peeyush singh Mar 04 '19 at 02:24
  • `for ( int i = 0; i <= 10; i++)` [What happens in the condition (second block) when `i` is `9` (the last index of `Arr`)?](https://rextester.com/AMRA3808) – ProgrammingLlama Mar 04 '19 at 02:25
  • 1
    Thanks John, I feel pretty dumb I keep forgetting arrays begin at 0 and not 1. But hopefully this error will stick in my head. "Index out of array bounds" to me was something like the data couldn't be accessed not that the values exceeded the size of the array. As you can tell i'm still pretty new at this. – DeprievedSense Mar 04 '19 at 02:35
  • @DeprievedSense No worries. The common error messages will become familiar over time :) – ProgrammingLlama Mar 04 '19 at 02:48

1 Answers1

1

Replace for ( int i = 0; i <= 10; i++) with for ( int i = 0; i < 10; i++)

otherwise, the index goes from 0 to 10, which is 11 values.

Better yet, use the array .Length property

for ( int i = 0; i < arr.Length; i++)
{
    // Do things with arr[i]
}
John Alexiou
  • 28,472
  • 11
  • 77
  • 133