Write C++ program to delete all duplicate elements from 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. #define MAX_SIZE 100 // Maximum size of the array
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. int arr[MAX_SIZE]; // Declares an array of size 100
  8. int num; // Total number of elements in array
  9. int i, j, k;
  10.  
  11. //Enter size of array
  12. cout<<"Enter size of the array : ";
  13. cin>>num;
  14.  
  15. //Reading elements of array
  16. cout<<"Enter elements in array : ";
  17. for(i=0; i<num; i++)
  18. {
  19. cin>>arr[i];
  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.  
  48. cout<<"\nArray elements after deleting duplicates : ";
  49. for(i=0; i<num; i++)
  50. {
  51. cout<<"\t"<<arr[i];
  52. }
  53.  
  54. return 0;
  55. }

Result

C++ language techstudy.org

     





Related Topics




Popular Posts