C Programm to Find same elements in two arrays

In this c programming we will write find same elements from two different arrays.

  • First take two arrays with size p and q
  • Assign values to both arrays
  • Now take 3rd array r  which will store the similar elements from the two arrays
  • Now Loop the two arrays by compare each element with other array
  • If the elements are same in the condition, then add that element into the the array r
  • Now print the array r, which will return the same elements from the given array

 

Let's write program

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

 

Output:

Enter the length of the first array:4
Enter 4 elements of the first array
1
34
23
15

Enter the length of the second array:5
Enter 5 elements of the second array
2
14
32
34
15

The common elements in the two arrays are:
34
15

 

Subscribe For Daily Updates