Java program to count distinct element in an array

Count distinct element in an array

In this section, we will learn, how to print the Count distinct element 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
they are  10,20,9,6,2

java Program to Counting distinct elements
java Program to Counting distinct elements in an 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 D Count function.

 

D Count(int a[], int n)

Step 1. Initialze temp variable with zero.

Step 2.  Initialize 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 code

Method 1

import java.util.*;
public class Main
{
public static void main (String[]args){
//creating scanner class
Scanner sc = new Scanner (System.in);
//create a new array
int[] a = new int[50];
//taking input the size for the array
System.out.println ("enter size of an array");
//create a size variable for the input
int size = sc.nextInt ();
// printing the statement for taking the input
System.out.println ("enter elements of an array b");
// looping through the array to take input in the array
for (int i = 0; i < size; i++){
// appendening int the array with the help of nextInt
a[i] = sc.nextInt ();
}
//calling the function and adding the statement for the input
System.out.println ("total distinct number of element " +
DCount (a, size));
}

// create a static functions named Dcount for counting the element
public static int DCount (int a[], int n) {
// create a variable for the count to register
int res = 0;
//loop for the checking if the variable
for (int i = 0; i < n; i++){
//new variable
int j;
//loop for checking the value
for (j = 0; j < i; j++)
//condition for check
if (a[i] == a[j])
break;
//condition to increse the count
if (i == j){
//incrementing the count
res++;
}
}
//returning the count ending the function
return res;
}
}

Output

output
//Test case 1
enter size of an array
5
enter elements of an array
12
12
13
14
13
total distinct number of element 3
//Test case 2
enter size of an array
5
enter elements of an array
10
20
30
30
10
total distinct number of element 3