- Define two arrays of a certain size and assign elements of your choice to both the arrays. Let's assume that we created two arrays called p and q, both of size four elements:
Figure 1.11
- Define one more array. Let's call it array r, to be used for storing the elements that are common between the two arrays.
- If an element in array p exists in the array q, it is added to array r. For instance, if the element at the first location in array p, which is at p[0], does not appear in array q, it is discarded, and the next element, at p[1], is picked up for comparison.
- And if the element at p[0] is found anywhere in array q, it is added to array r, as follows:
Figure 1.12
- This procedure is repeated with other elements of array q. That is, p[1] is compared with q[0], q[1], q[2], and q[3]. If p[1] is not found in array q, then before inserting it straightaway into array r, it is compared with the existing elements of array r to avoid repetitive elements.
- Because the element at p[1] appears in array q and is not already present in array r, it is added to array r as follows:
Figure 1.13
The commoninarray.c program for establishing common elements among the 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;
k=0;
printf("Enter the length of the first array:");
scanf("%d",&m);
printf("Enter %d elements of the first array\n",m);
for(i=0;i<m;i++ )
scanf("%d",&p[i]);
printf("\nEnter the length of the second array:");
scanf("%d",&n);
printf("Enter %d elements of the 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])
{
if(!ifexists(r,k,p[i]))
{
r[k]=p[i];
k++;
}
}
}
}
if(k>0)
{
printf("\nThe common elements in the two arrays are:\n");
for(i = 0;i<k;i++)
printf("%d\n",r[i]);
}
else
printf("There are no common elements in the two arrays\n");
}
Now, let's go behind the scenes to understand the code better.