Advertisement
ivandrofly

C# - Insert in middle and discard

Nov 27th, 2019
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.23 KB | None | 0 0
  1. using System;
  2.  
  3. namespace InsertInPosition
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             int[] items = { 2, 13, 0, 0, 20, 0, 0, 0 };
  10.  
  11.             int position = 2;
  12.  
  13.             int item = 200;
  14.  
  15.  
  16.             // insert *item into position *position
  17.  
  18.             // there is two solutiion
  19.             // 1 - discard the last item when inserting a new itme in middle of the list
  20.             // 2 - resizing the array when inserting a new item in middle of the list
  21.  
  22.             // solution one:
  23.             int len = items.Length;
  24.  
  25.             // store the current value in position
  26.             int t = items[position];
  27.  
  28.             for (int i = position; i + 1 < len; i++)
  29.             {
  30.                 items[i] = item;
  31.                 item = t;
  32.                 if (i + 1 < len)
  33.                 {
  34.                     t = items[i + 1];
  35.                 }
  36.             }
  37.  
  38.             DisplayArray(items);
  39.             Console.WriteLine("done");
  40.             Console.ReadLine();
  41.         }
  42.  
  43.         static void DisplayArray(int[] items)
  44.         {
  45.             foreach (var item in items)
  46.             {
  47.                 Console.Write(item + ",");
  48.             }
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement