Muhammad Adeel

Muhammad Adeel

  • NA
  • 55
  • 14.2k

Inserting into Array (C#)

Sep 12 2014 12:39 PM
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 ).


 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();

Answers (3)