Write C# program to delete all duplicate elements from an 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

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. using System;
  2. class Program
  3. {
  4. static void Main()
  5. {
  6. int[] arr = new int[100];
  7. int num; // Total number of elements in array
  8. int i, j, k;
  9.  
  10. //Reads size of the array
  11. Console.WriteLine("Enter size of the array: ");
  12. num = Convert.ToInt32(Console.ReadLine());
  13.  
  14. //Reads elements in array
  15. Console.WriteLine("Enter elements in the array: ");
  16. for (i = 0; i < num; i++)
  17. {
  18. arr[i] = Convert.ToInt32(Console.ReadLine());
  19. }
  20.  
  21.  
  22. // Finding all duplicate elements in array
  23.  
  24. for (i = 0; i < num; i++)
  25. {
  26. for (j = i + 1; j < num; j++)
  27. {
  28. //If any duplicate found */
  29. if (arr[i] == arr[j])
  30. {
  31. // Delete the current duplicate element
  32. for (k = j; k < num; k++)
  33. {
  34. arr[k] = arr[k + 1];
  35. }
  36.  
  37. //Decrement size after removing duplicate element
  38. num--;
  39.  
  40. // If shifting of elements occur then don't increment j
  41. j--;
  42. }
  43. }
  44. }
  45.  
  46. // Print array after deleting duplicate elements
  47. Console.WriteLine("\nArray elements after deleting duplicates : ");
  48. for (i = 0; i < num; i++)
  49. {
  50. Console.WriteLine(arr[i]);
  51. }
  52.  
  53. Console.ReadLine();
  54. }
  55.  
  56. }

Result

C# language techstudy

     





Related Topics




Popular Posts