java Write a function foo (int [] arr1. int[] arr2) that returns true if arr2 co
ID: 3581267 • Letter: J
Question
java
Explanation / Answer
CheckElements.java
import java.util.Arrays;
public class CheckElements {
public static void main(String[] args) {
//Declaring and initializing integer type arrays
int arr1[]={1,2,3,4,5};
int arr2[]={1,6,3,9,4,2,5,7};
//calling the method by passing arr1 and arr2 as arguments
boolean bool=foo(arr1,arr2);
/* If the method returns true then if block of code will get executed
* If not,else block of code will get executed.
*/
if(bool==true)
System.out.println("Array2 contains all the elements that are in Array1");
else
System.out.println("Array2 not contains all the elements that are in Array1");
}
//This method will check whether all the elements in arr1 are present in arr2
private static boolean foo(int[] arr1, int[] arr2) {
//Declaring variable
int count=0;
//This for loop will check whether the elements in arr1 are present in arr2
for(int i=0;i<arr1.length;i++)
{
for(int j=0;j<arr2.length;j++)
{
if(arr1[i]==arr2[j])
count++;
}
}
if(count==arr1.length)
return true;
else
return false;
}
}
________________________
Output:
Array2 contains all the elements that are in Array1
________________________
CheckElements1.java
import java.util.Arrays;
public class CheckElements1 {
public static void main(String[] args) {
//Declaring and initializing integer type arrays
int arr1[]={1,2,3,4,5};
int arr2[]={4,0,6};
//calling the method by passing arr1 and arr2 as arguments
boolean bool=foo(arr1,arr2);
/* If the method returns true then if block of code will get executed
* If not,else block of code will get executed.
*/
if(bool==true)
System.out.println("Array2 contains all the elements that are in Array1");
else
System.out.println("Array2 not contains all the elements that are in Array1");
}
//This method will check whether all the elements in arr1 are present in arr2
private static boolean foo(int[] arr1, int[] arr2) {
//Declaring variable
int count=0;
//This for loop will check whether the elements in arr1 are present in arr2
for(int i=0;i<arr1.length;i++)
{
for(int j=0;j<arr2.length;j++)
{
if(arr1[i]==arr2[j])
count++;
}
}
if(count==arr1.length)
return true;
else
return false;
}
}
_________________________
Output:
Array2 not contains all the elements that are in Array1
_______Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.