user2805351 - 1 year ago 99
C Question

# C program to find Union and intersection

following is my code:

``````#include <stdio.h>

void arrays()
{
int i,n,j;
printf("Enter the size of the arrays:\n");
scanf("%d",&n);

int a1[n];
int a2[n];
int intersection[2*n], unions[n];
printf("Enter elements of the first array:\n");

for (i = 0; i < n; i++)
{
scanf("%d",&a1[i]);
}
printf("Enter elements of the second array:\n");
for (j = 0; j < n; j++)
{
scanf("%d",&a2[j]);
}
int indexs = -1, indexu = -1;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
unions[++indexu] = a1[j];
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if(a1[i] == a2[j])
{
intersection[++indexs] = a2[j];
}
else
{
unions[++indexu] = a2[j];
}
}
}

printf("Intersection:\n");
printf("Union:\n");
for(i = 0; i < indexs; i++)
printf("%d",intersection[i]);
for (j = 0; j < indexu; j++)
printf("%d" ,unions[j]);
}
``````

Right now, I am having the trouble to find the union and intersection. I am trying to fix my loops, but I cannot find where is the problem
The way I am doing it is to first compare the first array with second array. Since union means all the elements in both array. then second is to find the duplicated number will go to intersection first. or if there is no element that stored in the union. it will go to union array too.
Can anyone help?
Thanks

One of the problems is in your output part.

``````printf("Intersection:\n");
printf("Union:\n");
for(i = 0; i < indexs; i++)
printf("%d",intersection[i]);
for (j = 0; j < indexu; j++)
printf("%d" ,unions[j]);
``````

This code snippet prints out both `"Intersection:\n"` and `"Union:\n"` before printing array contents. That's why you think it will not show intersection.

The correct code should be:

``````printf("Intersection:\n");
for(i = 0; i <= indexs; i++)
printf("%d",intersection[i]);
printf("\n");
printf("Union:\n");
for (j = 0; j <= indexu; j++)
printf("%d" ,unions[j]);
printf("\n");
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download