ให้ผู้ใช้ป้อนตัวเลขในอาร์เรย์ซึ่งมีองค์ประกอบที่ซ้ำกัน
ตอนนี้ มาเขียนโค้ดเพื่อลบตัวเลขหรือองค์ประกอบที่ซ้ำกันในอาร์เรย์ และสร้างอาร์เรย์ที่มีองค์ประกอบเฉพาะที่ไม่ซ้ำกัน
ตัวอย่างเช่น
อธิบายตัวอย่างด้านล่าง −
- ข้อมูลที่ผู้ใช้ป้อนคือ 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("\nArray 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