Miscellaneous Program(Remove Duplicate Elements)

  • April 10, 2022
  • C
Matrix multiplication

When an array contains the same number of elements in both sorted and unsorted order, the elements of the array are referred to as duplicate elements. And we must remove duplicate elements or elements with the same number from an array in order for the resultant array to contain only unique elements.

There is an integer type array arr[10] that contains 5, 8, 3, 3, 5, 9 elements, for example. 3 and 5 appear twice in this array. As a result, these elements are duplicates. We get 5, 8, 3,9 elements after removing duplicate elements from an array arr[].

Let us look at the code:

#include <stdio.h>  

int main ()  
{  
    // declare local variables   
    int arr[20], i, j, k, size;  
      
    printf (" Define the number of elements in an array: ");  
    scanf (" %d", &size);  
      
    printf (" \n Enter %d elements of an array: \n ", size);  
    // use for loop to enter the elements one by one in an array  
    for ( i = 0; i < size; i++)  
    {  
        scanf (" %d", &arr[i]);  
    }  
      
      
    // use nested for loop to find the duplicate elements in array  
    for ( i = 0; i < size; i ++)  
    {  
        for ( j = i + 1; j < size; j++)  
        {  
            // use if statement to check duplicate element  
            if ( arr[i] == arr[j])  
            {  
                // delete the current position of the duplicate element  
                for ( k = j; k < size - 1; k++)  
                {  
                    arr[k] = arr [k + 1];  
                }  
                // decrease the size of array after removing duplicate element  
                size--;  
                  
            // if the position of the elements is changes, don't increase the index j  
                j--;      
            }  
        }  
    }  
      
      
    /* display an array after deletion or removing of the duplicate elements */  
    printf (" \n Array elements after deletion of the duplicate elements: ");  
      
    // for loop to print the array  
    for ( i = 0; i < size; i++)  
    {  
        printf (" %d \t", arr[i]);  
    }  
    return 0;  
}  

Output:

Define the number of elements in an array: 4
Enter 4 elements of an array: 
 1 1 2 2
 Array elements after deletion of the duplicate elements:  1 	 2 	

Note: also read about the Miscellaneous Program(Palindrome Number)

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

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