dmilicev

are_all_array_elements_different.c

Sep 28th, 2020
120
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3.     are_all_array_elements_different.c
  4.  
  5.     Are all the elements of the array different from each other.
  6.     Check if all array elements are distinct (unique).
  7.  
  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. void ShowArray( char text[], int array[], int n )
  18. {
  19.     int i;
  20.  
  21.     printf("%s", text);
  22.  
  23.     for(i=0;i<n;i++)
  24.         printf("%2d", array[i]);
  25.  
  26.     printf("\n");
  27. }
  28.  
  29. // returns 1 if all elements are distinct (unique, different from each other)
  30. // otherwise returns 0
  31. int all_array_elements_are_distinct( int arr[], int size )
  32. {
  33.     int i, j;
  34.  
  35.     for (i=0; i<size; i++)
  36.         for (j=i+1; j<size; j++)
  37.             if (arr[i] == arr[j])
  38.                 return 0;
  39.  
  40.     return 1;
  41. }
  42.  
  43.  
  44. int main(void)
  45. {
  46.     int arr1[10] = {2,5,3,7,4,8,1,0,9,6};
  47.     int arr2[10] = {2,5,3,7,5,8,1,0,9,6};
  48.     int n1 = sizeof(arr1) / sizeof(arr1[0]);    // or n1 = sizeof(arr1) / sizeof(int);
  49.     int n2 = sizeof(arr2) / sizeof(arr2[0]);    // or n2 = sizeof(arr2) / sizeof(int);
  50.  
  51.     ShowArray("\n Array arr1[] is: ",arr1,n1);
  52.  
  53.     if ( all_array_elements_are_distinct(arr1,n1) )
  54.         printf("\n All array elements are distinct (unique, different from each other). \n");
  55.     else
  56.         printf("\n There are repeating elements in the array. \n");
  57.  
  58.     ShowArray("\n Array arr2[] is: ",arr2,n2);
  59.  
  60.     if ( all_array_elements_are_distinct(arr2,n2) )
  61.         printf("\n All array elements are distinct (unique, different from each other). \n");
  62.     else
  63.         printf("\n There are repeating elements in the array. \n");
  64.  
  65.     return 0;
  66.  
  67. } // main()
  68.  
RAW Paste Data Copied