在C中多次出现的数组元素?
数组是具有相同数据类型长度的元素的容器,需要预先定义。元素可以在数组中以任何顺序出现,并且可以出现任何次数。因此,在此程序中,我们将发现在数组中出现多次的元素。
问题描述-我们给了一个数组arr[],我们必须在其中找到要在应用程序中重复打印的元素。
让我们举个例子来更好地理解这一点。
例,
Input: arr[] = {5, 11, 11, 2, 1, 4, 2} Output: 11 2
说明
我们有一个数组arr,其中包含一些元素,首先,我们将比较复制函数中下一个元素的元素,该函数用于查找数组中的重复元素。在重复函数中,我们使用循环在给定数组中查找重复元素,如果条件相反,则使用条件检查数组元素中出现一次的数组元素计数,如果出现一次以上,则计数为1,然后如果计数大于1,将分别增加count,则该元素将被打印在屏幕上。
算法
Input : arr[], n the length of array. Step 1 : For i -> 0 to n, Follow step 2, Step 2 : For each element of the array. Do : Step 2.1 : For j -> i to n repeat step 2.2 - 2.3. Step 2.2 : if (arr[i] == arr[j]) -> print arr[i] Step 2.3 : else {// do nothing}
示例
#include <stdio.h> int main() { int arr[] = {21, 87, 212, 109, 41, 21}; int n=7; printf("The repeat elements of the array are : "); int *count = (int *)calloc(sizeof(int), (n - 2)); int i; for (i = 0; i < n; i++) { if (count[arr[i]] == 1) printf(" %d ", arr[i]); else count[arr[i]]++; } return 0; }
输出结果
The repeat elements of the array are : 21