C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Remove duplicate elements

C Program: Delete Duplicate Elements from an Array

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i, j, k;

 

    // Input size of array

    printf("Enter number of elements in the array: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Remove duplicate elements

    for (i = 0; i < n; i++) {

        for (j = i + 1; j < n; j++) {

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

                // Shift elements to the left

                for (k = j; k < n - 1; k++) {

                    arr[k] = arr[k + 1];

                }

                n--;  // Reduce array size

                j--;  // Recheck the new element at position j

            }

        }

    }

 

    // Display array after removing duplicates

    printf("\nArray after deleting duplicate elements:\n");

    for (i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

 

    printf("\n");

    return 0;

}

Output

 
INPUT :
Enter number of elements in the array: 10
Enter 10 elements:
2 5 3 2 8 5 9 1 3 5

OUTPUT :
Array after deleting duplicate elements:
2 5 3 8 9 1

Explanation

  1. The user enters array elements.
  2. The outer loop picks each element, while the inner loop checks for duplicates.
  3. When a duplicate is found, all elements after it are shifted left to overwrite it.
  4. The array size (n) is decreased accordingly.
  5. The resulting array contains only unique elements.