C program to print all unique element in an array

Write a C program to read elements in an array and print all unique element present in array. C program to find unique/distinct elements in an array.

Example: If elements of the array are: 1, 2, 3, 5, 1, 5, 20, 2, 12, 10
All unique elements in the array are: 3, 20, 12, 10

Required knowledge:

Basic C programming, For loop, Array

Program:

/**
 * C program to print all unique elements in array
 */

#include <stdio.h>

int main()
{
    int arr[100], size, isUnique;
    int i, j, k; //Used for loops

    /*
     * Reads size of the array
     */
    printf("Enter size of array: ");
    scanf("%d", &size);

    /*
     * Reads elements in array
     */
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    /*
     * Removes all duplicate elements from array
     */
    for(i=0; i<size; i++)
    {
        /* Assumes that the current array element is unique */
        isUnique = 1;

        for(j=i+1; j<size; j++)
        {
            /*
             * If any duplicate element is found
             */
            if(arr[i]==arr[j])
            {
                /* Remove the duplicate element */
                for(k=j; k<size-1; k++)
                {
                    arr[k] = arr[k+1];
                }

                size--;
                j--;
                isUnique = 0;
            }
        }

        /*
         * If array element is not unique
         * then also remove the current element
         */
        if(isUnique != 1)
        {
            for(j=i; j<size-1; j++)
            {
                arr[j] = arr[j+1];
            }

            size--;
            i--;
        }
    }

    /*
     * Prints all unique elements in array
     */
    printf("\nAll unique elements in the array are: ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", arr[i]);
    }

    return 0;
} 
Output
X
_
Enter size of array: 10
Enter elements in array: 1 2 3 5 1 5 20 2 12 10

All unique elements in the array are: 3      20      12      10

Happy coding ;)


You may also like

Labels: , ,