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.

Example

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

Working

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 : ");
    scanf("%d",&n);
    int arr[n];
    int newarr[n];
    printf("enter elements : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&arr[i]);
    }
    for(i=0; i<n; i++)
    {
        count = 0;
       for(j=0;j<=i;j++)
        {
            if(arr[i]==arr[j])
            {
                count++;
            }
        }
        if(count==1)
        {
            newarr[unique] = arr[i];
            unique++;
        }
    }
    printf("total distinct number of element : %d",unique);
    for(i=0; i<unique; i++)
    {
        printf("%d ",newarr[i]);
    }
    return 0;
}  
output
Elements of array
12 2 12 3 9
total distinct number of element : 3
12 3 9