C# Program to find union and intersection of two arrays


In this program, You will learn how to find union and intersection of two arrays in C#.


1st list is: 1 2 3 4 5

2nd list is: 3 4 5

Union is: 1 2 3 4 5

Intersection is: 3 4 5

Example: How to find union and intersection of two arrays in C#.

using System;
public class Program
{
	static void printUnion(int[] arr1, int[] arr2, int len1, int len2)
	{
		int f, i, j, k = 0;
		int[] arr3 = new int[100];
		for (i = 0; i < len1; i++)
		{
			arr3[k] = arr1[i];
			k++;
		}

		for (i = 0; i < len2; i++)
		{
			f = 0;
			for (j = 0; j < len1; j++)
			{
				if (arr2[i] == arr1[j])
				{
					f = 1;
				}
			}
			if (f == 0)
			{
				arr3[k] = arr2[i];
				k++;
			}
		}

		Console.Write("Union of Two Array is :");
		for (i = 0; i < k; i++)
		{
			Console.Write(arr3[i] + " ");
		}
	}

	static void printIntersection(int[] arr1, int[] arr2, int len1, int len2)
	{
		int[] arr3 = new int[100];
		int i, j, k = 0;

		for (i = 0; i < len1; i++)
		{
			for (j = 0; j < len2; j++)
			{
				if (arr1[i] == arr2[j])
				{
					arr3[k] = arr1[i];
					k++;
				}
			}
		}

		Console.Write("\nIntersection of Two Array is :");
		for (i = 0; i < k; i++)
		{
			Console.Write(arr3[i] + " ");
		}
	}

	public static void Main(string[] args)
	{
		int[] arr1 = new int[5];
		int[] arr2 = new int[3];

		Console.Write("Enter first array elements:");
		for (int i = 0; i < arr1.Length; i++)
		{
			arr1[i] = Convert.ToInt32(Console.ReadLine());
		}

		Console.Write("Enter second array elements:");
		for (int i = 0; i < arr2.Length; i++)
		{
			arr2[i] = Convert.ToInt32(Console.ReadLine());
		}

		printUnion(arr1, arr2, arr1.Length, arr2.Length);
		printIntersection(arr1, arr2, arr1.Length, arr2.Length);
	}
}

Output:

Enter first array elements:10
20
30
40
50
Enter second array elements:30
40
50
Union of Two Array is :10 20 30 40 50 
Intersection of Two Array is :30 40 50