# Count distinct elements of an array using java

## Count distinct elements of an array

In this section, we will learn, how to print the distinct number in an array in java language.

Given an integer array, we have to print all the distinct element of the input array. input array may contain duplicate elements, we have to print one element only once.

#### Example

`input: a[]={10,20,10,9,6,2,6,20}Output:  5there are five distinct elements in the array.they are  10,20,9,6,2`

now we will see the java program and working to find the distinct element in the array.

### Working

Step 1. Initialize arrays.

Step 2. Declare the scanner class for taking input.

Step 3. take array size from the user.

Step 4. Take an element of the array from the user.

Step 5.  Print the total distinct number of the array by calling DCount function.

DCount(int a[], int n)

Step 1. Initialise temp variable with zero.

Step 2.  Initialise two for-loop for checking the similar elements.

Step 3.  check the condition if i and j are equal then increase a temporary variable by one.

Step 4. Return the main temporary variable.

### Java program to count distinct elements of an array

`import java.util.Scanner;public class Main{    public static int DCount(int a[],int n)    {        int res=0;                for(int i=0;i<n;i++)        {            int j;            for (j = 0; j < i; j++)               if (a[i] == a[j])                    break;            if (i == j)            {                res++;            }        }        System.out.println();        return res;     }     public static void main(String[] args)      {          Scanner sc=new Scanner(System.in);          int[] a=new int[50];          System.out.println("enter size of an array");          int size=sc.nextInt();          System.out.println("enter elements of an array");          for(int i=0;i<size;i++)          {                 a[i]=sc.nextInt();          }          System.out.println("total distinct number of element "+DCount(a,size));     }}`

### Output

`enter size of an array6enter elements of an array123242total distinct number of element 4`

Please Login/Signup to comment