พยายามลบตัวเลขเดิมที่มีอยู่ในอาร์เรย์ อาร์เรย์ผลลัพธ์ประกอบด้วยองค์ประกอบที่ไม่ซ้ำกัน
ตรรกะในการลบองค์ประกอบที่ซ้ำกันในอาร์เรย์ เป็นดังนี้ −
for(i=0;i<number;i++){
for(j = i+1; j < number; j++){
if(a[i] == a[j]){
for(k = j; k <number; k++){
a[k] = a[k+1];
}
j--;
number--;
}
}
} ตรรกะในการแสดงตัวเลขหลังจากลบรายการที่ซ้ำกันมีดังนี้ -
for(i=0;i<number;i++){
printf("%d ",a[i]);
} โปรแกรม
ต่อไปนี้เป็นโปรแกรม C เพื่อลบองค์ประกอบที่ซ้ำกันในอาร์เรย์
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[50],i,j,k, count = 0, dup[50], number;
printf("Enter size of the array\n");
scanf("%d",&number);
printf("Enter Elements of the array:\n");
for(i=0;i<number;i++){
scanf("%d",&a[i]);
dup[i] = -1;
}
printf("Entered element are: \n");
for(i=0;i<number;i++){
printf("%d ",a[i]);
}
for(i=0;i<number;i++){
for(j = i+1; j < number; j++){
if(a[i] == a[j]){
for(k = j; k <number; k++){
a[k] = a[k+1];
}
j--;
number--;
}
}
}
printf("\nAfter deleting the duplicate element the Array is:\n");
for(i=0;i<number;i++){
printf("%d ",a[i]);
}
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Enter size of the array 10 Enter Elements of the array: 1 1 2 4 3 5 6 5 7 1 Entered element are: 1 1 2 4 3 5 6 5 7 1 After deleting the duplicate element, the Array is: 1 2 4 3 5 6 7