How to remove duplicate elements from an array in C language?

In C language, you can remove duplicate elements from an array using the following methods:

  1. Create a new array to store the unique elements.
  2. Traverse the original array and check if each element is already existing in the new array.
  3. If it does not exist, add the element to a new array.
  4. Finally, the elements in the new array are the result of removing duplicates from the original array.

Here is a sample code:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int arr[MAX_SIZE] = {1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9};
    int new_arr[MAX_SIZE];
    int new_size = 0;
    
    for (int i = 0; i < MAX_SIZE; i++) {
        int is_duplicate = 0;
        
        for (int j = 0; j < new_size; j++) {
            if (arr[i] == new_arr[j]) {
                is_duplicate = 1;
                break;
            }
        }
        
        if (!is_duplicate) {
            new_arr[new_size] = arr[i];
            new_size++;
        }
    }
    
    // 打印去重后的数组
    for (int i = 0; i < new_size; i++) {
        printf("%d ", new_arr[i]);
    }
    
    return 0;
}

The output will be: 1 2 3 4 5 6 7 8 9.

bannerAds