You’re not quite understanding how arrays are structured. An IndexOutOfRange exception is thrown when you try to access part of an array that does not exist. For example, if I have an array with 5 elements in it, and I try to access the 6th, it will give me the OutOfRange exception, because there is no 6th element.
Now, you also need to consider that arrays are what we call 0-indexed. This means that, when accessing an array, to get the first element in the array, you ask for index 0 (that is, array[0] will give you the first element. This has some implications that you haven’t quite picked up on, that I will try and explain with an example. Let’s say I have an array of length 6 (that means there are 6 elements in the array, and array.Length is equal to 6). It looks like this:
{ a, b, c, d, e, f }
Now, I’ll annotate this with the index you need to call to access the specific element of the array:
i = 0 1 2 3 4 5
{ a, b, c, d, e, f }
So if we call array_ we will get the corresponding item in the array when i is any of the values seen there. The implication here is something you might have spotted already. The array contains 6 elements. The length of the array is 6. But, because the first element is indexed with 0, the last is indexed with 5, not 6. Zero indexing means the last element of an array can be gained like this: array[array.Length-1]._
Now, let’s have a look at your for loop:
for(i=0;i<=move.Length;i++)
Now, this means that i will progress from 0 to the length of the array move, inclusive. Let’s assume move has 3 elements. On the first run on this loop, i will be 0, so calling move* equates to move[0], which, as we’ve said, is the first element of the array.*
On the next iteration, move* equates to move[1], which is the second element.*
On the third iteration, move* becomes move[2], which is the third element of the array.*
Now, at the start of the next iteration, i is equal to 3, so we check the condition: i<=move.Length, and find that 3<=3, so we continue again, and find that this time, move_ becomes move[3], which gets the fourth element of the array… but the array only has 3 elements, so there is no fourth element to get. This causes the program to throw and OutOfRange exception, to prevent you from accessing uninitialised spaces in memory.
Hopefully this has helped you to understand what is causing the problem, and if you’ve read this through properly, you’ll be able to fix it._