This blog is under construction

Thursday 25 July 2013

C program to print unique elements in an array

Write a C program to print the unique elements in an array.


  #include <stdio.h>
  #define MAX 256
  #define DUP 1

  int main() {
        int i, j, n, value[MAX][2];

        /* get the number of array elements from the user */
        printf("Enter the number of elements:");
        scanf("%d", &n);

        /* get the array entries from the user */
        printf("Enter your array elements:\n");
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", &value[i][0]);
                value[i][1] = 0;
        }

        /* mark the elements that are not unique  */
        for (i = 0; i < n; i++) {

                if (value[i][1])
                        continue;

                for (j = i + 1; j < n; j++) {
                        if (value[i][0] == value[j][0]) {
                                value[i][1] = value[j][1] = DUP;
                        }
                }

        }

        /* print the unique elements in the given array */
        printf("Unique elements in the given array:\n");
        for (i = 0; i < n; i++) {
                if (!value[i][1])
                        printf("%d ", value[i][0]);
        }

        printf("\n");

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements:5
  Enter your array elements:
  Data[0]: 10
  Data[1]: 22 
  Data[2]: 30
  Data[3]: 10
  Data[4]: 22
  Unique elements in the given array:
  30 


No comments:

Post a Comment