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();
VulpesPosted Sep 12, 2014, 1:23 PM
The main problem you have is that, once arrays are created, their length can't be changed. However, you can deal with this as follows:
1. Create a new array whose length is one more than the old one.
2. Copy the old array elements to the new one.
3. Assign the new array to the original array variable.
4. Set the new array variable to null.
This is, more or less, what the Arrray.Resize method does.
Try this revised code:
Anoop Kumar SharmaPosted Sep 12, 2014, 1:32 PM
In Above Code, you declared int[] LinearArr = new int[length];
and the trying to store value more than its storing capacity
see this in you code LinearArr[length + 1] = LinearArr[length];
That's why you get IndexOutOfRangeException with message Index was outside the bounds of the array.
Hope this will help you.
Wim SturkenboomPosted Sep 12, 2014, 1:30 PM
So no surprises ;)