C Program to establish the difference between two Arrays
This program will be designed to establish the difference between two arrays. In this program, two arrays will be entered by the user. Then, the program will compare each element of the first array with the corresponding element of the second array and output the difference between them.
When we talk about the difference between two sets, we are referring to all the elements of the first set which don’t appear in the second set. All the elements of the first set which are not common to the second set are referred to as the difference between the two sets. The difference in sets p and q, for example, will be denoted by p – q. If array p, for example, has the elements {1, 2, 3, 4}, and array q has the elements {2, 4, 5, 6}, then the difference between the two arrays, p – q, will be {1,3}. Let’s find out how this is done.
#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;
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])
{
break;
}
}
if(j==n)
{
if(!ifexists(r,k,p[i]))
{
r[k]=p[i];
k++;
}
}
}
printf("\nThe difference of the two array is:\n");
for(i = 0;i<k;i++)
printf("%d\n",r[i]);
}
The concept of creating a for loop is fairly straightforward. But there are a few ways to get the job done. In this case, I’ll be using a “for” loop, which allows you to loop through an array. Here are the steps:
- Define your variables. This includes declaring the arrays and what values each array will contain. In this case, we are declaring 2 arrays: one will hold the values 1 to 10 (indexed starting at 0) and the other will hold the values 11 to 20 (indexed starting at 1).
- Declare the first array:
- Loop through the second array and copy its value into the first array.
- Display the values.
- Go back to step 3 and repeat until the end of the arrays are reached.