I am trying to write a program that has a universal array and an array A and B. I need to find the union and intersection of A and B, but for now I am just working on the union. Below is the code I have written so far. It compiles with no errors but doesn't print the union of A and B. Can somebody please help me?
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int U[20], A[20], B[20], U1[20]; // U1 should stores the elemnts that are the result of A U B.
int i, j, flag;
int lengthU, lengthA, lengthB, lengthU1;
lengthU = 0;
lengthA = 0;
lengthB = 0;
printf("\n Enter no more than 20 elements (Integer Between -100 and 100) for the universal set. \n");
for (i = 0; i < 20; i++)
{
printf("Please enter a number between -100 and 100\n");
scanf("%i", &U[i]);
if((U[i] < -100) || (U[i] > 100))
{
break;
}
else
{
lengthU = lengthU + 1;
}
}
printf("Elements of the universal set you entered:\n");
for (i = 0; i < lengthU; i++)
{
printf("\t%d", U[i]);
}
printf("\n\n Enter no more than 20 elements (Integer Between -100 and 100) for set A. \n");
for (i = 0; i < 20; i++)
{
printf("Please enter a number between -100 and 100\n");
scanf("%i", &A[i]);
if((A[i] < -100) || (A[i] > 100))
{
break;
}
else
{
lengthA = lengthA + 1;
}
}
printf("Elements of the set A you entered:\n");
for (i = 0; i < lengthA; i++)
{
printf("\t%d", A[i]);
}
printf("\n\n Enter no more than 20 elements (Integer Between -100 and 100) for set B. \n");
for (i = 0; i < 20; i++)
{
printf("Please enter a number between -100 and 100\n");
scanf("%i", &B[i]);
if((B[i] < -100) || (B[i] > 100))
{
break;
}
else
{
lengthB = lengthB + 1;
}
}
printf("Elements of set B you entered:\n");
for (i = 0; i < lengthB; i++)
{
printf("\t%d", B[i]);
}
for(i=0; i<lengthA; i++)
{
U1[i] = A[i];
}
lengthU1 = lengthA;
for(i=0; i<lengthB; i++)
{
flag = 0;
j=0;
while ((j<lengthU1) && (flag==0))
{
if (B[i]=U1[j])
{
flag = 1;
}
j = j+1;
}
if(flag==0)
{
U1[lengthU1]=B[i];
lengthU1=lengthU1 + 1;
}
}
printf("\n\n The Union of A and B is: ");
printf ("\t%d", U1[i]);
return 0;
}