C Programm to Difference between two arrays

In this cprogramming example we will write find the difference between two arrays

  • Define two arrays, A and B, and add elements to them
  • Define one more array C, which will be used for storing the elements which are difference between the two arrays.
  • Pick one element from array A and compare it with all the elements of the
  • array B.
  • If the element of array A exists in array B, discard that element and pick
  • the next element from array A and repeat steps from 3.
  • If the element of array A does not exist in array B, add that element in
  • array C. While adding that element into array C, ensure that it does not
  • contain in array C.
  • Repeat steps 3 to 5 until all the elements of array A are compared.
  • Print the elements in Array c which will represents the difference between given two arrays

 

let's write the programm

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

 

Output:

Enter length of first array:4
Enter 4 elements of first array
2
3
34
25

Enter length of second array:2
Enter 2 elements of second array
34
22

The difference of the two array is:
2
3
25

 

Subscribe For Daily Updates