문제
두 개의 루프를 사용하여 배열에서 반복되지 않는 요소를 찾습니다. 하나는 현재 요소에 대한 것이고 다른 하나는 요소가 이미 배열에 존재하는지 여부를 확인하는 것입니다.
해결책
아래 주어진 예를 고려하십시오 -
15, 15, 16, 15, 13, 15
여기서 배열의 반복되지 않는 요소는 16과 13입니다.
알고리즘
배열에서 고유하거나 반복되지 않는 요소를 찾는 방법은 아래에 제공된 알고리즘을 참조하십시오.
1단계 - 배열을 선언하고 런타임에 배열 요소를 입력합니다.
2단계 - 배열 탐색을 시작하고 현재 요소가 이미 배열에 있는지 확인합니다.
3단계 - 배열에 이미 존재하는 경우 배열의 다음 요소로 이동하고 계속합니다.
4단계 - 그렇지 않은 경우 요소를 반복되지 않는 요소로 출력합니다.
예시
다음은 배열에서 고유하거나 반복되지 않는 요소를 찾는 C 프로그램입니다. -
#include <stdio.h>
#include <stdlib.h>
int uniqueEle(int array[], int n){
int i,j;
int count = 1;
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
if(array[i] == array[j] && i != j)
break;
}
if(j == n ){
printf("\nunique elements in an array is [%d] : %d \n",count,array[i]);
++count;
}
}
return -1;
}
int main(){
int n,i;
printf("\nEnter no: of elements : ");
scanf("%d",&n);
int array[n];
printf("\nenter the array elements : ");
for(i = 0; i < n; i++){
scanf("%d",&array[i]);
}
uniqueEle(array, n);
return 0;
} 출력
위의 프로그램이 실행되면 다음과 같은 출력을 생성합니다 -
Run 1: Enter no: of elements: 5 enter the array elements : 11 11 15 16 13 unique elements in an array is [1] : 15 unique elements in an array is [2] : 16 unique elements in an array is [3] : 13 Run 2: Enter no: of elements: 4 enter the array elements : 11 12 11 11 unique elements in an array is [1] : 12