TheBulgarianWolf

Array-Add New Element + Erase Element

Apr 20th, 2020
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.06 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace OnlineExercise15._4
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {  
  13.             Console.WriteLine("Enter the length of the array: ");
  14.             int length = int.Parse(Console.ReadLine());
  15.             int[] array = new int[length];
  16.             for(int i = 0; i < array.Length; i++)
  17.             {
  18.                 Console.Write("Element [{0}] = ", i+1);
  19.                 int l = int.Parse(Console.ReadLine());
  20.                 array[i] = l;
  21.                 Console.WriteLine();
  22.             }
  23.  
  24.             Console.WriteLine("In which position would you like to put the new element: ");
  25.             int positionOne = int.Parse(Console.ReadLine());
  26.             Console.WriteLine("Enter the number you want to enter in that position: ");
  27.             int elementValue = int.Parse(Console.ReadLine());
  28.             int[] newArray = new int[length + 1];
  29.             for(int m = 0; m < positionOne; m++)
  30.             {
  31.                 newArray[m] = array[m];
  32.             }
  33.             newArray[positionOne] = elementValue;
  34.             for(int u = positionOne + 1; u < newArray.Length; u++)
  35.             {
  36.                 newArray[u] = array[u - 1];
  37.             }
  38.             //Printing the new array
  39.             for(int s = 0; s < newArray.Length; s++)
  40.             {
  41.                 Console.Write(newArray[s] + " ");
  42.             }
  43.             Console.WriteLine("Now enter the position which you want to erase: ");
  44.             int positionTwo = int.Parse(Console.ReadLine());
  45.  
  46.             for (int f = 0; f < positionTwo; f++)
  47.             {
  48.                 array[f] = newArray[f];
  49.             }
  50.  
  51.             for(int g = positionTwo + 1; g < newArray.Length; g++)
  52.             {
  53.                 array[g - 1] = newArray[g];
  54.             }
  55.            
  56.             for(int h = 0; h < array.Length; h++)
  57.             {
  58.                 Console.Write(array[h] + " ");
  59.             }
  60.             Console.ReadKey();
  61.         }
  62.     }
  63. }
Add Comment
Please, Sign In to add comment