Union and intersection of two integer arrays.
#include<stdio.h>
int main() {
int a[5],b[5],uni[20],inter[5];
int i,j,k=0,t;
// Inserting two arrays.
printf("Enter the elements of 1st array : \n");
for (i=0; i<5; i++){
scanf("%d",&a[i]);
}
printf("Enter the elements of 2nd array : \n");
for (i=0; i<5; i++){
scanf("%d",&b[i]);
}
// Sorting of both arrays.
for (i=0; i<5; i++){
for (j=i; j<5; j++){
if(a[i]>a[j]){
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for (i=0; i<5; i++){
for (j=i; j<5; j++){
if(b[i]>b[j]){
t=b[i];
b[i]=b[j];
b[j]=t;
}
}
}
// For union of two matrix.
i=j=0;
while (i<5 && j<5){
if(a[i]<b[j]){
uni[k]=a[i];
i++; k++;
}
else if (a[i]>b[j]){
uni[k]=b[j];
j++; k++;
}
else{
uni[k]=a[i];
i++; j++; k++;
}
}
if (i<5){
for (;i<5;i++){
uni[k]=a[i];
i++; k++;
}
}
else if(j<5){
for (;j<5;j++){
uni[k]=b[j];
j++; k++;
}
}
// For intersection of two matrix.
t=0;
for (i=0; i<5; i++){
for (j=0; j<5; j++){
if (a[i]==b[j]){
inter[t]=b[j];
t++;
}
}
}
printf("Union :\n");
for (i=0; i<k; i++){
printf("%d ",uni[i]);
}
printf("\nIntersection :\n");
for (i=0; i<t; i++){
printf("%d ",inter[i]);
}
return 0;
}
No comments:
Post a Comment