FY_BCA_C_SLIP 15_2



Slip no: 15_2 C Program to Find Union & Intersection of 2 Arrays


#include <stdio.h> #define SIZE 5

int find_intersection(int array1[], int array2[], int intersection_array[])

{
int i = 0, j = 0, k = 0;

while ((i < SIZE) && (j < SIZE))
{
if (array1[i] < array2[j])
{
i++;
}
else if (array1[i] > array2[j])
{
j++;
}
else
{
intersection_array[k] = array1[i]; i++;
j++;
k++;
}
}
return(k);
}

int find_union(int array1[], int array2[], int union_array[])
{
int i = 0, j = 0, k = 0;
while ((i < SIZE) && (j < SIZE))
{
if (array1[i] < array2[j])
{
union_array[k] = array1[i]; i++;
k++;
}
else if (array1[i] > array2[j])
{
union_array[k] = array2[j]; j++;
k++;
}
else
{
union_array[k] = array1[i]; i++;
j++;
k++;
}
}

if (i == SIZE)
{
while (j < SIZE)
{
union_array[k] = array2[j]; j++;
k++;
}
}
else
{
while (i < SIZE)
{
union_array[k] = array1[i]; i++;
k++;
}
}
return(k);
}


int main()
{
int array1[SIZE], array2[SIZE], intersection_array[SIZE], union_array[SIZE*2]; int num_elements,i,j;

//input elements of Array1
printf("\n Enter the elements of Array 1:\n");
for (i = 0; i < SIZE; i++)
{
j = i + 1;
printf("\n Enter element %d: ", j); scanf("%d", &array1[i]);
}

//input elements of Array2
printf("\nEnter the elements of Array 2: \n"); for (i = 0; i < SIZE; i++)
{
j = i + 1;
printf("\n Enter element %d: ", j); scanf("%d", &array2[i]);
}

//Find Intersection
num_elements = find_intersection(array1, array2, intersection_array); printf("\n\n Intersection is: ");
printf("{ ");
for (i = 0; i < num_elements; i++)
{
printf("%d ", intersection_array[i]);
}
printf("}");

//Find Union
num_elements = find_union(array1, array2, union_array); printf("\n\n Union is: ");
printf("{ ");
for (i = 0; i < num_elements; i++)
{
printf("%d ", union_array[i]);
}
printf("}");

}

No comments:

Post a Comment