Write a program that counts the number of common elements in 2 sorted arrays
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#define MAXNUM 100
void main(void)
{
int i, j, count=0, n1, n2, X[MAXNUM], Y[MAXNUM];
do{
printf("Enter the dimension of X: ");
scanf("%d",&n1);
}while(n1<=0 || n1>MAXNUM);
printf("\nEnter the numbers in ascending order of X:\n");
scanf("%d", &X[0]);
for(i=1;i<n1;i++)
do{
scanf("%d", &X[i]);
}while(X[i]<X[i-1]);
do{
printf("Enter the dimension of Y: ");
scanf("%d",&n2);
}while(n2<=0 || n2>MAXNUM);
printf("\nEnter the numbers in ascending order of Y:\n");
scanf("%d", &Y[0]);
for(i=1;i<n2;i++)
do{
scanf("%d", &Y[i]);
}while(Y[i]<Y[i-1]);
i=0; j=0;
while((i<n1)&&(j<n2))
{
/*if both elements are common*/
if(X[i]==Y[j])
{
i++;
j++;
count++;
}
else/*advance the smaller*/
(X[i]>Y[j])? j++: i++;
}
printf("\nNumber of common elements: %d\n", count);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
N-ary tree