How can duplicates be removed and output in the C language?
In C language, arrays and loops can be utilized to remove duplicate values and display the result.
Here is an example code:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 2, 5, 6, 4, 7, 8, 7, 9}; // 示例数组
int n = sizeof(arr) / sizeof(arr[0]); // 数组长度
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) { // 如果有重复值
for (int k = j; k < n - 1; k++) { // 后面的元素往前移动
arr[k] = arr[k + 1];
}
n--; // 数组长度减1
j--; // 循环变量j减1,以便继续比较移动后的元素
}
}
}
printf("删除重复值后的数组为:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Executing this code will result in:
删除重复值后的数组为:1 2 3 4 5 6 7 8 9
The code first defines an example array “arr” and calculates the length “n” of the array using the sizeof operator. Then it uses two nested loops to compare the elements in the array one by one. If a duplicate value is found, the following elements are moved forward by one position and the array length “n” is recalculated. Finally, the code outputs the array with duplicate values removed using a loop.