Write a program with the below specifications/requirements: (Java Language)
-Create two arrays of size 10 to hold integers
- Initialize the two arrays with random numbers in the range {0,19}
-Print the contents of the two arrays after initialization
-Print the numbers that exist in both arrays( i.e intersection of arrays)
import java.util.Scanner;
import java.util.Random;
import java.lang.*;
public class Print
{
public static void main(String[] args)
{
//creation of two arrays
int arr1[]=new int[10];//declaration and instantiation
int arr2[]=new int[10];//declaration and instantiation
int inter[]= new int[10]; //declaration and instantiation used for
intersection elements
Random r = new Random(); //create a random object
int i,j,k,a;
//loop to generate 10 random values between 0 to 19 (both
inclusive) and assign to arr1
for(i=0;i<10;i++)
arr1[i]=r.nextInt((19 - 0) + 1) + 0; //generate random integer in
the range 0 to 19 and assign
//loop to generate 10 random values between 0 to 19 (both
inclusive) and assign to arr2
for(i=0;i<10;i++)
arr2[i]=r.nextInt((19 - 0) + 1) + 0;//generate random integer in
the range 0 to 19 and assign
//print the first array elements
System.out.println("First Array elements are");
for(i=0;i<10;i++)
System.out.print(arr1[i]+" ");
//print the second array elements
System.out.println("\nSecond Array elements are");
for(i=0;i<10;i++)
System.out.print(arr2[i]+" ");
//compute the intersection of both the arrays
//this block will only store the common elements without
repetation
k=0;//k index is used for intersection array
for(i=0;i<10;i++) //loop for first array
{
for(j=0;j<10;j++) //loop for second array
{
if(arr1[i]==arr2[j]) //compare the element of array1 and
array2
{
for(a=0;a<k;a++) //loop to compare whether the common element is
already in
//intersection array or not
if(arr1[i]==inter[a]) //if already there then terminate the
loop
break;
if(a==k) //when element is not in intersection the a will equal to
k, i.e/ loop will
//completely executed
{
inter[k]=arr1[i];//assign the common element into intersection
array
k++; //increase the index
}
}
}
}
//print the intersection elements
System.out.println("\nThe elements in Both arrays are");
for(a=0;a<k;a++) //loop will continue from 0 to k. where k
indicates the number of elements
//in intersection array
System.out.print(inter[a]+" ");
}
}
OUTPUT
Get Answers For Free
Most questions answered within 1 hours.