C Program for establishing common elements among the two Arrays

CWC
2 Min Read

C Program for establishing common elements among the two Arrays

You will be asked to enter the elements of the two matrices using the nested for loops. The elements in the matrix are entered in row-major order, in other words, all the elements of the first row are entered first, followed by all the elements of the second row, and so on

Finding the common elements in two arrays is akin to finding the intersection of two sets. Define two arrays of a certain size and assign elements of your choice to both the arrays.

#include
#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");
}
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version