Write C# program to insert an element in array


Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.


techstudy.org

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

  1.  
  2. using System;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. int[] arr = new int[100];
  8. int i, num, size, position;
  9.  
  10. // Reading array size & elements in the array
  11. Console.WriteLine("Enter size of the array: ");
  12. size = Convert.ToInt32(Console.ReadLine());
  13. Console.WriteLine("Enter elements in the array: ");
  14. for(i=0; i<size; i++)
  15. {
  16. arr[i] = Convert.ToInt32(Console.ReadLine());
  17. }
  18.  
  19. //Reading element to insert & position of the element
  20.  
  21. Console.WriteLine("Enter element to insert: ");
  22. num = Convert.ToInt32(Console.ReadLine());
  23.  
  24. Console.Write("Enter the element position: ");
  25. position = Convert.ToInt32(Console.ReadLine());
  26.  
  27. //checking elements valis position
  28.  
  29. if (position > size + 1 || position <= 0)
  30. {
  31. Console.WriteLine("Invalid position! Please enter position between 1 to " + num);
  32. }
  33. else
  34. {
  35. //Inserting element in an array & increasing the size of the array
  36.  
  37. for (i = size; i >= position; i--)
  38. {
  39. arr[i] = arr[i - 1];
  40. }
  41. arr[position - 1] = num;
  42. size++;
  43.  
  44. // Printing new array with new element
  45.  
  46. Console.WriteLine("Array elements after insertion :");
  47.  
  48. for (i = 0; i < size; i++)
  49. {
  50. Console.WriteLine(arr[i] + "\t");
  51. }
  52. }
  53.  
  54. Console.ReadLine();
  55. }
  56.  
  57. }

Result

C# language techstudy

     





Related Topics


Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.