I am getting "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" error at run time while trying to print values of array using foreach loop. I debugged the problem in visual studio and can see that i in foreach is going till 7 which is out of bounds. foreach loop automatically takes all the elements of an array so please help me in understanding the reason for the error? Below is the function:
void Sort(int[] A)
{
for (int i = 1; i < A.Length; i++)
{
int key = A[i];
int j = i - 1;
while (j >= 0 && A[j] > key)
{
A[j + 1] = A[j];
j = j - 1;
}
A[j + 1] = key;
}
foreach (int i in A)
Console.Write(A[i].ToString());
}
}
}