사용자가 중복 요소를 포함하는 배열에 숫자를 입력하도록 합니다.
이제 배열에서 반복되는 숫자나 요소를 삭제하고 중복되지 않는 고유한 요소로 배열을 만드는 코드를 작성해 보겠습니다.
예:
예는 아래에 설명되어 있습니다 -
- 사용자 입력은 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