Advertisement
dmilicev

delete_all_duplicate_elements_from_array_v1.c

Apr 25th, 2020
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. /*
  2.  
  3.     delete_all_duplicate_elements_from_array_v1.c
  4.  
  5.     Delete duplicate elements in array of n integers.
  6.  
  7. https://codeforwin.org/2015/07/c-program-to-delete-duplicate-elements-from-array.html?fbclid=IwAR1YsI0DRAiND3K8qQ3SDUOenu-n48EvRoAKMVXH8CwvA847OcizqMCXBYg
  8.  
  9.     You can find all my C programs at Dragan Milicev's pastebin:
  10.  
  11.     https://pastebin.com/u/dmilicev
  12.  
  13. */
  14.  
  15. #include <stdio.h>
  16.  
  17. #define MAX_SIZE 100 // Maximum size of the array
  18.  
  19.  
  20. // Displays an array of n integers with prompt text
  21. void display_array_of_integers( char text[], int array[], int n ) {
  22.  
  23.     int i;
  24.  
  25.     printf("\n\n%s ( size = %d )\n\n", text, n );
  26.  
  27.     for( i=0; i<n ; i++ )               // display of array items
  28.         printf("%4d", array[i] );
  29.  
  30.     printf("\n");
  31. }
  32.  
  33.  
  34. // Delete duplicate elements in array of n integers
  35. void delete_all_duplicate_elements_from_array( int arr[], int *n )
  36. {
  37.     int i, j, k;                        // Loop control variables
  38.  
  39.     for(i=0; i<(*n); i++)
  40.     {
  41.         for(j=i+1; j<(*n); j++)
  42.         {
  43.             if(arr[i] == arr[j])        // if any duplicate found
  44.             {
  45.                 for(k=j; k<(*n); k++)   // delete the current duplicate element
  46.                 {
  47.                     arr[k] = arr[k + 1];
  48.                 }
  49.                 (*n)--;                 // decrement n after removing duplicate element
  50.                 j--;                    // if shifting of elements occur then don't increment j
  51.             } // if(arr[i] == arr[j])
  52.         } // for(j=i+1; j<n; j++)
  53.     } // for(i=0; i<n; i++)
  54. } // delete_all_duplicate_elements_from_array()
  55.  
  56.  
  57. int main(void)
  58. {
  59.     int arr[] = {10, 20, 10, 1, 100, 10, 2, 1, 5, 10};  // Declares an array of integers
  60.     int n = sizeof(arr)/sizeof(arr[0]);     // A way to get n, number of elements in array arr[]
  61.  
  62.     display_array_of_integers( "\n Before: ", arr, n );
  63.  
  64.     delete_all_duplicate_elements_from_array( arr, &n );
  65.  
  66.     display_array_of_integers( "\n After:  ", arr, n );
  67.  
  68.  
  69.     return 0;
  70. } // main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement