C Program to Find Common Elements in Two Arrays

In this post, Let's write a c program to find common elements in two arrays. 

Let’s assume we have following two sorted arrays p and q.

int p[] = {1,  3,  5,  7,  9};

int q[] = {1,  2,  3,  4,  5};

So the common elements in these two arrays are 1, 3, and 5.

C Program to Find Common Elements in Two Arrays

Let's create a file named commoninarray.c and add the following source code to it.

#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])
			{
				if(!ifexists(r,k,p[i]))
				{
					r[k]=p[i];
					k++;
				}
			}
		}
	}
	if(k>0)
	{
	printf("\nThe common elements in the two array are:\n"); 

	for(i = 0;i<k;i++)
		printf("%d\n",r[i]); 
	}
	else
		printf("There are no common elements in two arrays\n");
}

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

Enter length of first array:5
Enter 5 elements of first array
1
3
5
7
9

Enter length of second array:5
Enter 5 elements of second array
1
2
3
4
5

The common elements in the two array are:
1
3
5

Comments