How to do it… 

  1. Define two arrays, p and q, of a certain size and assign elements only to array p. We will leave array q blank.
  2. These will be our source and target arrays, respectively. The target array will contain the resulting unique elements of the source array.
  1. After that, each of the elements in the source array will be compared with the existing elements in the target array. 
  2. If the element in the source array exists in the target array, then that element is discarded and the next element in the source array is picked up for comparison.
  3. If the source array element does not exist in the target array, it is copied into the target array.
  4. Let's assume that array p contains the following repetitive elements:

Figure 1.17
  1. We will start by copying the first element of the source array, p, into the target array, q, in other words, p[0] into array q[0], as follows:

Figure 1.18
  1. Next, the second array element of p, in other words, p[1], is compared with all the existing elements of array q. That is, p[1] is compared with array q to check whether it already exists in array q, as follows:

Figure 1.19
  1. Because p[1] does not exist in array q, it is copied at q[1], as shown in Figure 1.20: 

Figure 1.20
  1. This procedure is repeated until all the elements of array p are compared with array q. In the end, we will have array q, which will contain the unique elements of array p.

Here is the uniqueelements.c program for finding the unique elements in the first array:

#include<stdio.h>
#define max 100

int ifexists(int z[], int u, int v)
{
int i;
for (i=0; i<u;i++)
if (z[i]==v) return (1);
return (0);
}

void main()
{
int p[max], q[max];
int m;
int i,k;
k=0;
printf("Enter length of the array:");
scanf("%d",&m);
printf("Enter %d elements of the array\n",m);
for(i=0;i<m;i++ )
scanf("%d",&p[i]);
q[0]=p[0];
k=1;
for (i=1;i<m;i++)
{
if(!ifexists(q,k,p[i]))
{
q[k]=p[i];
k++;
}
}
printf("\nThe unique elements in the array are:\n");
for(i = 0;i<k;i++)
printf("%d\n",q[i]);
}

Now, let's go behind the scenes to understand the code better.