Muhammad Adeel
Muhammad Adeel

Reputation: 5

Inserting into Array (C#)

I am trying to insert an int value in int array at the user input index and getting an error: Index was outside the bounds of the array. The error is in the while loop, but the solution does not use any methods like Array.Add etc.

Console.WriteLine("Enter the length of Linear Array");
int length = Convert.ToInt32(Console.ReadLine());
int[] LinearArr = new int[length];
Console.WriteLine("Maximum number of input : {0}",length);
for (int i = 0; i < LinearArr.Length; i++)
{
    LinearArr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("What number you want to insert and at what index");
int InsertNum = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number :{0} and Index :{1}",InsertNum,k);

while (length>=k)
{
    LinearArr[length + 1] = LinearArr[length];
    length = length - 1;
}
LinearArr[k] = InsertNum;
length = length + 1;
Console.ReadLine();

Upvotes: 0

Views: 294

Answers (3)

Guvante
Guvante

Reputation: 19203

You may want to consider using a List<int> instead of an int[] as it provides an Insert function.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

When you define

int[] LinearArr = new int[length];

the valid indexes are 0..length-1. Therefore, this expression causes an out-of-range exception:

LinearArr[length + 1] = LinearArr[length];

neither length nor length+1 are valid indexes.

In order to fix this problem, allocate enough space in the array, and start moving elements at length-1:

int[] LinearArr = new int[length+1]; // Make space for an expansion
...
while (length > k) {
    LinearArr[length] = LinearArr[length-1];
    length--;
}

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Change your while loop condition from:

while (length >= k)

to:

while (length > k)

as in current condition it will access last index which is not in the array.

Another mistake is your array is of size of value in the length variable:

LinearArr[length]

and in while loop you are accessing index greater then array length:

LinearArr[length + 1] = LinearArr[length]; // length +1 will give out of bounds error

Upvotes: 1

Related Questions