Write a Program in C to Remove the Duplicate Elements in an Sorted And Unsorted Array

Write a Program in C to remove duplicate elements in an array (sorted and unsorted array cases) is discussed here. Given an array, all the duplicate elements of the array are removed.

For example, consider the array.

case 1: Remove duplicates from sorted array

 

Input: arr = {1, 2, 3, 4, 4}

 

Output: arr = {1, 2, 3, 4}

 

case 2: Remove duplicates from unsorted array

 

Input: arr = {9, 2, 7, 4, 7}

 

Output: arr = {9, 2, 7, 4}


Duplicate Elements from Array




Program in C

#include<stdio.h>
#include<conio.h>
int main()
{
    int a[20], i, j, k, n;

    printf("\nEnter array size: ");
    scanf("%d", &n);

    printf("\nEnter %d array element: ", n);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }

    printf("\nOriginal array is: ");
    for(i = 0; i < n; i++)
    {
        printf(" %d", a[i]);
    }

    printf("\nNew array is: ");
    for(i = 0; i < n; i++)
    {
        for(j = i+1; j < n; )
        {
            if(a[j] == a[i])
            {
                for(k = j; k < n; k++)
                {
                    a[k] = a[k+1];
                }
                n--;
            }
            else
            {
                j++;
            }
        }
    }

    for(i = 0; i < n; i++)
    {
        printf("%d ", a[i]);
    }
}


Output

Enter array size: 5

Enter 5 array element: 9 2 7 4 7

Original array is:  9 2 7 4 7
New array is: 9 2 7 4 

Enter array size: 5

Enter 5 array element: 1 2 3 4 4 

Original array is:  1 2 3 4 4
New array is: 1 2 3 4 

Admin

Hi This is the Admin of CodingSoln. Currently Pursuing B. Tech Computer Science and Engineering form KIIT University India

Post a Comment

Previous Post Next Post