consider two sets of integer values stored as arrays x and y of size m and n respectively. For example, x[5]={2,68,10,90,4} and y[4]={68,3,10,22}. Write a program to print the intersection (intersection returns the elements that are common in both sets) of these two sets, i.e., the set {68, 10}.
In JAVA Programming language
Program code to copy:-
import java.util.Scanner;
public class Intersection {
public static void main(String[] args) {
//Create scanner object for
standard input
Scanner scan = new
Scanner(System.in);
//Prompt & read the size of
array from user
System.out.print("Enter the size of
first array: ");
int m = scan.nextInt();
//Declare array of m size
int x[] = new int[m];
//Prompt & read m elements for first array
System.out.print("Enter the elements for first array: ");
for(int i = 0;i < m;i++)
x[i] = scan.nextInt();
//Prompt & read the size of array from user
System.out.print("Enter the size of second array: ");
int n = scan.nextInt();
//Declare array of n size
int y[] = new int[n];
//Prompt & read n elements for second array
System.out.print("Enter the elements for second array: ");
for(int i = 0;i < n;i++)
y[i] = scan.nextInt();
System.out.print("The intersection of two sets: ");
int found=0;
//Loop to find the intersection of two arrays
for(int i=0;i < m;i++)
{
for(int j=0;j < n;j++)
{
if(x[i]==y[j])
{
found=1;
}
}
if(found==1)
System.out.print(x[i]+" ");
found=0;
}
}
}
Screenshot of output:-
Get Answers For Free
Most questions answered within 1 hours.