編寫一個 C 程式,以在陣列中刪除重複數字


讓使用者在陣列中輸入包含重複元素的數字。

現在,讓我們編寫一個程式碼來刪除陣列中的重複數字或元素,並建立一個不包含重複項的唯一元素陣列

例如,

下面解釋了一個示例 −

  • 使用者輸入為 12、30、12、45、67、30。
  • 輸出為 12、30、45、67(刪除重複項後)。

程式

以下是 C 程式以在陣列中刪除重複數字

 即時演示

#include <stdio.h>
#define MAX 100 // Maximum size of the array
int main(){
   int array[MAX]; // Declares an array of size 100
   int size;
   int i, j, k; // Loop variables
   /* Input size of the array */
   printf("enter the size of array : ");
   scanf("%d", &size);
   /* Input elements in the array */
   printf("Enter elements in an array : ");
   for(i=0; i<size; i++){
      scanf("%d", &array[i]);
   }
   /*find the duplicate elements in an array:
   for(i=0; i<size; i++){
      for(j=i+1; j<size; j++){
         /* If any duplicate found */
         if(array[i] == array[j]){
            /* Delete the current duplicate element */
            for(k=j; k<size; k++){
               array[k] = array[k + 1];
            }
            /* Decrement size after removing duplicate element */
            size--;
            /* If shifting of elements occur then don't increment j */
            j--;
         }
      }
   }
   printf("
Array elements after deleting duplicates : ");/*print an array after deleting the duplicate elements.    for(i=0; i<size; i++){       printf("%d\t", array[i]);    }    return 0; }

輸出

輸出如下 −

enter the size of array : 10
Enter elements in an array : 23 12 34 56 23 12 56 78 45 56
Array elements after deleting duplicates : 23 12 34 56 78 45

更新於:15-3-2021

1K+ 次瀏覽

開啟你的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.