Write C++ program to print all unique element in an array


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

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

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int arr[100], size, isUnique;
  7. int i, j, k;
  8.  
  9. //Reads size of the array
  10. cout<<"Enter size of array: ";
  11. cin>>size;
  12.  
  13. //Reads elements in array
  14. cout<<"Enter elements in array: ";
  15. for(i=0; i<size; i++)
  16. {
  17. cin>>arr[i];
  18. }
  19.  
  20. //Removing all duplicate elements from the array
  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. //Printing all unique elements in array
  61. cout<<"All unique elements in the array are: ";
  62. for(i=0; i<size; i++)
  63. {
  64. cout<<arr[i]<<"\t";
  65. }
  66. return 0;
  67. }
  68.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts