C Program to Find Difference Between Two Arrays

In this post, let's write a C program to find the difference between two arrays.

When we talk about the difference between two sets or arrays, we are referring to all the elements of the first array that don't appear in the second array. In essence, all the elements in the first array that are not common to the second array are referred to as the difference between the two sets. The difference in sets p and q, for example, will be denoted by p – q.

C Program to Find Difference Between Two Arrays

#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;
	k=0;
	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]); 
}

Output:

Enter length of first array:4
Enter 4 elements of first array
1
2
3
4
Enter length of second array:4
Enter 4 elements of second array
2
4
5
6
The difference of the two array is:
1
3

Let's understand the above C program step by step:

  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 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.

Comments