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:  5

there 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.

Distinct element

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 array
6
enter elements of an array
1
2
3
2
4
2
total distinct number of element 4

Please Login/Signup to comment