How can duplicate elements be removed from an array in C language?

To remove duplicate elements from an array, you can use a nested loop to iterate through the array, comparing each element with the ones after it. If they are equal, then remove the duplicate element. Here is an example code:

#include <stdio.h>

void removeDuplicates(int arr[], int size)
{
    int i, j, k;
    
    // 遍历数组中的每一个元素
    for (i = 0; i < size; i++) {
        // 查找后面的元素是否与当前元素相等
        for (j = i + 1; j < size;) {
            if (arr[j] == arr[i]) {
                // 如果相等,则将后面的元素往前移动
                for (k = j; k < size - 1; k++) {
                    arr[k] = arr[k + 1];
                }
                size--; // 数组长度减1
            } else {
                j++; // 继续查找下一个元素
            }
        }
    }
}

int main()
{
    int arr[] = {1, 2, 3, 1, 2, 4, 5, 6, 2, 7};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    removeDuplicates(arr, size);
    
    // 打印去重后的数组
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

The output result is: 1 2 3 4 5 6 7

bannerAds