-1
        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.

Muhammad Muazzam
  • 2,810
  • 6
  • 33
  • 62
vnu thaya
  • 3
  • 2
  • 2
    What are you trying to achieve? Why don't you use a [List](https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx) instead? – Salah Akbari Jul 09 '17 at 13:41
  • arr.Length is 6; you assign it to n, n is now 6, n is n + 1, n is now 7, in your loop i = n which is 7, arr[i-1] is arr[6] and, arr[6] doesnt exist, that is why you get indexOutOfRange Exception, and you should use lists if you want to edit – sergenp Jul 09 '17 at 13:42
  • inserting an element on 1st index @S.Akbari – vnu thaya Jul 09 '17 at 13:44
  • I can use list but I need to find how insert an element in array – vnu thaya Jul 09 '17 at 13:45
  • @vnuthaya You can't with an array, you need to use a `List` instead. – Salah Akbari Jul 09 '17 at 13:46
  • @sergenp if arr.Length is 7 ,last index is 6 right!!. there will be a arr[6]. Am I wrong!! – vnu thaya Jul 09 '17 at 13:48
  • Arrays are a fixed length data structure. If you want to "add" a value you actually have to create a new array. In fact that's what List does behind the scenes for you. – juharr Jul 09 '17 at 13:48
  • @vnuthaya arr length is not 7, it is 6, maybe you forgot to add another element to it? – sergenp Jul 09 '17 at 13:49
  • @vnuthaya, please let us know what are your requirements? You can't resize an array in C#, this collection type has a fixed length. If you want a collection that can be resized use List, LinkedList or any other collection classes that are based on List. Are you trying to _replace_ an element? Shift elements? Please describe your use case. – ironstone13 Jul 09 '17 at 14:07

3 Answers3

1
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<>

T.Aoukar
  • 653
  • 5
  • 19
0

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
Rajeev Ranjan
  • 3,588
  • 6
  • 28
  • 52
0

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]
Mudasir Younas
  • 864
  • 6
  • 10