C/C++ Program for Union of Two Arrays

example:

First array: {1, 3, 7, 9}

Second array: {1, 4, 6}

Union: {1, 3, 4, 7, 6, 9}

#include<stdio.h>
 
int main()
{
	int a1[20],a2[20],u[40],i,j,k,n,m;
	
	printf("Enter size of first array:");
	scanf("%d",&n);
	printf("Enter elements of first array in ascending order:\n");
	for(i=0;i<n;++i){
		scanf("%d",&a1[i]);
	}
	
	printf("\nEnter size of second array:");
	scanf("%d",&m);
	printf("Enter elements of second array in ascending order:\n");
	for(i=0;i<m;++i){
		scanf("%d",&a2[i]);
	}
	
	for(i=0,j=0,k=0;i<n&&j<m;){
		if(a1[i]<a2[j]){
			u[k]=a1[i];
			i++;
			k++;
		}
		else if(a1[i]>a2[j]){
			u[k]=a2[j];
			j++;
			k++;
		}
		else{
			u[k]=a1[i];
			i++;
			j++;
			k++;
		}
	}
	
	if(i<n){
		for(;i<n;++i){
			u[k]=a1[i];
			k++;
		}
	}
	else if(j<m){
		for(;j<m;++j){
			u[k]=a2[j];
			k++;
		}
	}
	
	printf("\nUnion of two arrays is:\n");
	for(i=0;i<k;++i){
		printf("%d ",u[i]);
	}
 
    return 0;
}

Output

Enter size of first array:4
Enter elements of first array in ascending order:
1 2 3 5

Enter size of second array:5
Enter elements of second array in ascending order:
1 3 5 7 9

Union of two arrays is:
1 2 3 5 7 9

Union of Two Unsorted Arrays

#include<stdio.h>
 
int main()
{
	int a1[20],a2[20],u[40],i,j,k,n,m,flag;
	
	printf("Enter size of first array:");
	scanf("%d",&n);
	printf("Enter elements of first array:\n");
	for(i=0;i<n;++i){
		scanf("%d",&a1[i]);
	}
	
	printf("\nEnter size of second array:");
	scanf("%d",&m);
	printf("Enter elements of second array:\n");
	for(i=0;i<m;++i){
		scanf("%d",&a2[i]);
	}
	
	k=0;
	for(i=0;i<n;++i){
		u[k]=a1[i];
		k++;
	}
	
	for(i=0;i<m;++i){
		flag=1;
		for(j=0;j<n;++j){
			if(a2[i]==a1[j]){
				flag=0;
				break;
			}
		}
		
		if(flag){
			u[k]=a2[i];
			k++;
		}
	}
	
	printf("\nUnion of two arrays is:\n");
	for(i=0;i<k;++i){
		printf("%d ",u[i]);
	}
 
    return 0;
}

Output

Enter size of first array:3
Enter elements of first array:
1 3 5

Enter size of second array:4
Enter elements of second array:
1 2 3 6

Union of two arrays is:
1 3 5 2 6

Leave a Comment

error: Alert: Content is protected!!