C program to delete all duplicate elements from an array

Write a C program to delete(remove) all duplicate elements from an array. C program to remove all duplicate integer values from an array. After performing delete operation the array should only contain unique integer value.

Example:
If elements of array are: 10, 20, 10, 1, 100, 10, 2, 1, 5, 10
After removing all duplicate elements
Elements of array are: 10, 20, 1, 100, 2, 5

Required knowledge:

Basic C programming, If else, For loop, Nested loop, Array

Program:

/**
 * C program to delete all duplicate elements from array
 */

#include <stdio.h>
#define MAX_SIZE 100 //Maximum size of the array

int main()
{
    int arr[MAX_SIZE]; //Declares an array of size 100
    int size; //Total number of elements in array
    int i, j, k; //Used for loop

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

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


    /*
     * Finds all duplicate elements in array
     */
    for(i=0; i<size; i++)
    {
        for(j=i+1; j<size; j++)
        {
            /* If any duplicate found */
            if(arr[i]==arr[j])
            {
                for(k=j; k<size; k++)
                {
                    arr[k] = arr[k+1];
                }

                /* Decrement size after removing one duplicate element */
                size--;

                /* If shifting of elements occur then don't increment j */
                j--;
            }
        }
    }


    /*
     * Print array after deleting duplicate elements
     */
    printf("\nArray elements after deleting duplicates : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", arr[i]);
    }

    return 0;
} 


Output
Enter size of the array : 10
Enter elements in array : 10 20 10 1 100 10 2 1 5 10

Array elements after deleting duplicates : 10    20    1    100    2    5

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment