Q57 Write a C program to remove duplicates in a sorted array.

#include<stdio.h>

int remove_duplicate(int arr[], int arr_size)

{

        int i, j = 0;

        printf(“Printing original array elements\n”);

        for(i = 0; i < arr_size; i++)

        {

                printf(“%d\t”,arr[i]);

        }

        /* Removing duplicates */

        for(i = 1; i < arr_size; i++)

        {

                if(arr[i] != arr[j])

                {

                        j++;

                        arr[j] = arr[i];

                }

        }

        /* The new array size is j+1*/

        arr_size = j+1;

        printf(“\nPrinting new array elements after removing duplicates\n”);

        for(i = 0; i < arr_size; i++)

        {

                printf(“%d\t”,arr[i]);

        }

        return (j+1);

}

int main()

{

        int arr[] = {10, 20, 30, 30, 40, 50, 50, 60};

        int arr_size = 8;

        int new_arr_size = 0;

        new_arr_size =  remove_duplicate(arr, arr_size);

        return 0;

}

Output:

$ ./a.exe

Printing original array elements

10      20      30      30      40      50      50      60

Printing new array elements after removing duplicates

10      20      30      40      50      60

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.