Write C# program to print all unique element in 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

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

  1. using System;
  2. class Program
  3. {
  4. static void Main()
  5. {
  6. int[] arr = new int[100];;
  7. int i, j, k, size, isUnique;
  8.  
  9. //Reads size of the array
  10. Console.WriteLine("Enter size of the array: ");
  11. size = Convert.ToInt32(Console.ReadLine());
  12. //Reads elements in array
  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. //Removing all duplicate elements from the array
  20.  
  21. for(i=0; i<size; i++)
  22. {
  23. // Assuming cuurent element is unique */
  24. isUnique = 1;
  25.  
  26. for(j=i+1; j<size; j++)
  27. {
  28.  
  29. //If any duplicate element is found
  30.  
  31. if(arr[i]==arr[j])
  32. {
  33. // Removing duplicate element
  34. for(k=j; k<size-1; k++)
  35. {
  36. arr[k] = arr[k+1];
  37. }
  38.  
  39. size--;
  40. j--;
  41. isUnique = 0;
  42. }
  43. }
  44.  
  45. /*
  46.   If array element is not unique
  47.   then also remove the current element
  48.   */
  49. if (isUnique != 1)
  50. {
  51. for (j = i; j < size - 1; j++)
  52. {
  53. arr[j] = arr[j + 1];
  54. }
  55.  
  56. size--;
  57. i--;
  58. }
  59. }
  60.  
  61. //Printing all unique elements in array
  62. Console.WriteLine("All unique elements in the array are: ");
  63. for (i = 0; i < size; i++)
  64. {
  65. Console.WriteLine(arr[i] + "\t");
  66. }
  67. Console.ReadLine();
  68. }
  69.  
  70. }

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/.