int[] arr = {4,3,6,7,9,12};
int n = arr.Length;
n = n + 1;
for (int i =n;i>2;i--) {
arr[i-1] = arr[i-2];
}
arr[0] = 4;
The above code returning
indexOutOfRangeexception.
int[] arr = {4,3,6,7,9,12};
int n = arr.Length;
n = n + 1;
for (int i =n;i>2;i--) {
arr[i-1] = arr[i-2];
}
arr[0] = 4;
The above code returning
indexOutOfRangeexception.
int n = arr.Length //n=6
n=n+1 //n=7
for(int i=n;i>2;i--){ //i=7
arr[i-1] //arr[6]
While clearly the last element is arr[5]. In C# arrays are of constant length, you can't change them, the only way to do that is to create a new array, or a better solution would be using List<>
Of course it will because of these
n = n + 1; // n = 7
for (int i =n;i>2;i--) { //Assining 7 to i
arr[i-1] = arr[i-2]; // trying to access arr[6] which is not valid
Your array is of Length
6 starting from 0.
In for
loop i becomes 7 and arr[7-1] = arr[6]
is out of range, maximum is arr[5]
ie:
arr[0]
arr[1]
arr[2]
arr[3]
arr[4]
arr[5]