Computer >> Computer tutorials >  >> Programming >> C programming

C program to perform union operation on two arrays


A union is a special data type available in C programming language that allows to store different data types in the same memory location. Unions provide an efficient way of using the same memory location for multiple-purpose.

Union operation

If array 1 = { 1,2,3,4,6}

    Array 2 = {1,2,5,6,7}

Then, union of array1 and array 2 is

Array1 U array 2 = {1,2,3,4,6} U {1,2,5,6,7}

                              = {1,2,3,4,5,6,7}

Set of all elements without repetition is called union.

The logic for union is as follows −

for(i=0;i<size1;i++){
   uni[j]=a[i];
   j++;
}
for(i=0;i<size2;i++){
   uni[j]=b[i];
   j++;
}

The logic for removing repeated elements is as follows −

int removerepeated(int size,int a[]){
   int i,j,k;
   for(i=0;i<size;i++){
      for(j=i+1;j<size;){
         if(a[i]==a[j]){
            for(k=j;k<size;k++){
               a[k]=a[k+1];
            }
            size--;
         }else{
            j++;
         }
      }
   }
   return(size);
}

Program

Following is the C program to perform union operation on two arrays −

#include<stdio.h>
int removerepeated(int size,int a[]);
void sort(int size,int a[]);
main(){
   int i,size1,size2,size,j=0,k;
   printf("Enter size of an array1\n");
   scanf("%d",&size1);
   printf("Enter size of an array2\n");
   scanf("%d",&size2);
   int a[size1],b[size2],uni[size1+size2];
   printf("Enter numbers for array 1\n");
   for(i=0;i<size1;i++){
      scanf("%d",&a[i]);
   }
   printf("Enter numbers for array 2\n");
   for(i=0;i<size2;i++){
      scanf("%d",&b[i]);
   }
   //union start
   for(i=0;i<size1;i++){
      uni[j]=a[i];
      j++;
   }
   for(i=0;i<size2;i++){
      uni[j]=b[i];
      j++;
   }
   //Sorting
   sort(size1+size2,uni);
   //Remove repeated elements
   size=removerepeated(size1+size2,uni);
   printf("Array afetr Union \n");
   for(i=0;i<size;i++){
      printf("%d\n",uni[i]);
   }
   //Sorting
}
int removerepeated(int size,int a[]){
   int i,j,k;
   for(i=0;i<size;i++){
      for(j=i+1;j<size;){
         if(a[i]==a[j]){
            for(k=j;k<size;k++){
               a[k]=a[k+1];
            }
            size--;
         }else{
            j++;
         }
      }
   }
   return(size);
}
void sort(int size,int a[]){
   int i,j,temp;
   for(i=0;i<size;i++){
      for(j=i+1;j<size;j++){
         if(a[i]>a[j]){
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
         }
      }
   }
}

Output

When the above program is executed, it produces the following result −

Enter size of an array1
4
Enter size of an array2
3
Enter numbers for array 1
1
2
3
4
Enter numbers for array 2
3
5
6
Array after Union
1
2
3
4
5
6