Write a method called is Unique that accepts an array of int
Solution
Method:
private static boolean isUnique(int[] arr) {
//Declaring variable
int count = 0;
/* This for loop will check whether the array
* elements contains Duplicates or not
*/
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
}
/* Count is equal to length of the array
* means no duplicates in the array
*/
if(count==arr.length)
return true;
else
return false;
}
_____________________
Complete program to make you Understood:
package org.students;
public class Demo {
public static void main(String[] args) {
int arr1[] = { 3, 8, 12, 2, 9, 17, 43, -8, -46 };
int arr2[] = { 4, 7, 3, 9, 12, -47, 3, 74 };
boolean bool = isUnique(arr1);
if (bool)
System.out.println(\"Elements in Array1 are unique\");
else
System.out.println(\"Elements in Array1 are not unique\");
boolean bool1 = isUnique(arr2);
if (bool1)
System.out.println(\"Elements in Array2 are unique\");
else
System.out.println(\"Elements in Array2 are not unique\");
}
private static boolean isUnique(int[] arr) {
//Declaring variable
int count = 0;
/* This for loop will check whether the array
* elements contains Duplicates or not
*/
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
}
/* Count is equal to length of the array
* means no duplicates in the array
*/
if(count==arr.length)
return true;
else
return false;
}
}
________________
output:
Elements in Array1 are unique
Elements in Array2 are not unique
________________Thank YOu

