首頁  >  文章  >  後端開發  >  在C語言中,出現多次的陣列元素是什麼?

在C語言中,出現多次的陣列元素是什麼?

WBOY
WBOY轉載
2023-09-05 09:05:101308瀏覽

在C語言中,出現多次的陣列元素是什麼?

Array是一個容器,其中包含相同資料類型的元素,長度需要事先定義。數組中的元素可以以任何順序和任意次數出現。因此,在這個程式中,我們將找出數組中出現多次的元素。

問題描述 - 我們已經給一個陣列arr[],我們需要找出陣列中重複出現的元素,並列印它們。

讓我們舉一個例子來更好地理解。

範例:

Input: arr[] = {5, 11, 11, 2, 1, 4, 2}
Output: 11 2

解釋

我們有一個包含一些元素的陣列arr,首先我們會在重複函數中比較下一個元素。重複函數用於在陣列中找到重複的元素。在重複函數中,我們使用循環來尋找給定數組中的重複元素。我們將使用if else條件來檢查數組元素的計數,如果數組元素出現一次,則計數為1,如果出現多次,則計數將相應地遞增。如果計數大於1,則該元素將列印在螢幕上。

演算法

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}

Example

的中文翻譯為:

範例

#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

以上是在C語言中,出現多次的陣列元素是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除