MATH IV

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Write a Program to find union and intersection of two set

#include <stdio.h>

void printArray(int arr[], int size) {

for (int i = 0; i < size; i++) {

printf("%d ", arr[i]);

printf("\n");

void findUnion(int arr1[], int size1, int arr2[], int size2) {

int i = 0, j = 0;

while (i < size1 && j < size2) {

if (arr1[i] < arr2[j]) {

printf("%d ", arr1[i++]);

} else if (arr2[j] < arr1[i]) {

printf("%d ", arr2[j++]);

} else {

printf("%d ", arr1[i++]);

j++;

while (i < size1) {

printf("%d ", arr1[i++]);

}
while (j < size2) {

printf("%d ", arr2[j++]);

printf("\n");

void findIntersection(int arr1[], int size1, int arr2[], int size2) {

int i = 0, j = 0;

while (i < size1 && j < size2) {

if (arr1[i] < arr2[j]) {

i++;

} else if (arr2[j] < arr1[i]) {

j++;

} else {

printf("%d ", arr1[i++]);

j++;

printf("\n");

int main() {

int arr1[] = {1, 3, 5, 7};

int arr2[] = {2, 4, 6, 7};

int size1 = sizeof(arr1) / sizeof(arr1[0]);


int size2 = sizeof(arr2) / sizeof(arr2[0]);

printf("Array 1: ");

printArray(arr1, size1);

printf("Array 2: ");

printArray(arr2, size2);

printf("Union: ");

findUnion(arr1, size1, arr2, size2);

printf("Intersection: ");

findIntersection(arr1, size1, arr2, size2);

return 0;

Output

Array 1: 1 3 5 7

Array 2: 2 4 6 7

Union: 1 2 3 4 5 6 7

Intersection: 7

Write a program to find difference between two set.


#include<stdio.h>

int main()

int a[10],b[10],c[10],d[10],m=0,k=0,n1,n2,l,i,j;

printf("Enter size of set A");


scanf("%d",&n1);

printf("Enter element of set");

for( i=0;i<n1;i++)

scanf("%d",&a[i]);

printf("Enter size of set B");

scanf("%d",&n2);

printf("Enter element of set");

for( i=0;i<n2;i++)

scanf("%d",&b[i]);

// logic for find A-B

for( i=0;i<n1;i++)

for(j=0;j<n2;j++)

if(b[j]==a[i])

break;

if(j==n2)

// here we check that is element already present in the set

// if present than ignore it otherwise add to the difference set

for(l=0;l<k;l++)

if(c[l]==a[i])

break;

if(l==k)
{

c[k]=a[i];

k++;

// logic for find B-A

for( i=0;i<n2;i++)

for(j=0;j<n1;j++)

if(b[i]==a[j])

break;

if(j==n1)

// here we check that is element already present in the set

//if present than ignore it otherwise add to the difference set

for(l=0;l<m;l++)

if(d[l]==b[i])

break;

if(l==m)

{
d[m]=b[i];

m++;

printf("Difference of A-B is:-\n");

for(i=0;i<k;i++)

printf("%d ",c[i]);

printf("\n");

printf("Difference of B-A is:-\n");

for(i=0;i<m;i++)

printf("%d ",d[i]);

return 0;

You might also like