In this article, we are going to find distinct element in array using java code.
Example:-
if n=5(size of ann array)
arr={45,23,5,23,45}, then the output will be 3.
Steps:-
- Take array input from user using scanner.
- Take a Boolean variable and initialize it true.
- Take a variable count and initialize it with 0 .
- Run a loop from i=0 to size of arrray-1.
- Run another loop from j=i-1 to j>=0.
- Inside second loop check if a[i] = a[j], then update Boolean varirable to false and break the loop,
- decrement j by 1.
- end of second loop
- if Boolean variable is true then increment count by 1.
- update Boolean variable to true.
- end of first loop.
- count will hold the number of distinct element in given array.
Java code to find distinct element in given array:-
package gangforcode;
import java.util.Scanner;
public class DistinctElements {
public static int CountDigits(int[] a,int n) {
int Count=0;
boolean isDistinct=true;
for(int i=0;i<n;i++) {
for(int j=i-1;j>=0;j--) {
if(a[i]==a[j]) {
isDistinct=false;
break;
}
}
if(isDistinct==true) {
Count++;
}
isDistinct=true;
}
return Count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int[]a=new int[n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
System.out.println(CountDigits(a,n));
}}
Output:-
You can use same logic to find distinct element in given array using another programing language like C, C++, Python.