C program to count distinct element in an array

Count distinct element in an array

In this section, we will learn, how to print the distinct number in an array in C 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.


input: a[]={10,20,10,9,6,2,6,20}

Output:  5
they are  10,20,9,6,2

java program to count-distinct elements in an array


Step 1. Input the size of array from the user.

Step 2. Input the elements of array from the user.

Step 3. Make the array unique. i.e it should contain only distinct element.

Step 4. Print the number of distinct element and distinct elements also.

C code

#include <stdio.h>  
int main()  
    int n, i , j, count=0, unique = 0;;
    printf("enter size : ");
    int arr[n];
    int newarr[n];
    printf("enter elements : ");
    for(i=0; i<n; i++)
    for(i=0; i<n; i++)
        count = 0;
            newarr[unique] = arr[i];
    printf("total distinct number of element : %d",unique);
    for(i=0; i<unique; i++)
        printf("%d ",newarr[i]);
    return 0;
Elements of array
12 2 12 3 9
total distinct number of element : 3
12 3 9