How to do it…

  1. Define two arrays, say p and q, of a certain size and assign elements of your choice to both the arrays.
  2. Define one more array, say r, to be used for storing the elements that represent the difference between the two arrays.
  3. Pick one element from array p and compare it with all the elements of the array q.
  4. If the element of array p exists in array q, discard that element and pick up the next element of array p and repeat from step 3.
  5. If the element of array p does not exist in array q, add that element in array r. Before adding that element to array r, ensure that it does not already exist in array r.
  6. Repeat steps 3 to 5 until all the elements of array p are compared.
  7. Display all the elements in array r, as these are the elements that represent the difference between arrays p and q.

The differencearray.c program to establish the difference between two arrays is as follows:

#include<stdio.h>
#define max 100

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

void main()
{
int p[max], q[max], r[max];
int m,n;
int i,j,k;
printf("Enter length of first array:");
scanf("%d",&m);
printf("Enter %d elements of first array\n",m);
for(i=0;i<m;i++ )
scanf("%d",&p[i]);
printf("\nEnter length of second array:");
scanf("%d",&n);
printf("Enter %d elements of second array\n",n);
for(i=0;i<n;i++ ) scanf("%d",&q[i]);
k=0;
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
if (p[i]==q[j])
{ break;
}
}
if(j==n)
{
if(!ifexists(r,k,p[i]))
{
r[k]=p[i];
k++;
}
}
}
printf("\nThe difference of the two array is:\n");
for(i = 0;i<k;i++)
printf("%d\n",r[i]);
}

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