문제
사용자가 런타임에 배열에서 요소를 검색하고 검색 후 화면에 결과를 표시하는 C 프로그램을 작성하십시오. 검색 요소가 배열에 없으면 검색 요소를 찾을 수 없습니다.
해결책
배열은 하나의 이름으로 공통 요소 그룹을 유지하는 데 사용됩니다.
배열 연산은 다음과 같습니다 -
- 삽입
- 삭제
- 검색
알고리즘
포인터를 사용하여 요소를 배열로 검색하는 알고리즘 참조 -
1단계 - 요소 수를 선언하고 읽습니다.
2단계 - 런타임에 배열 크기를 선언하고 읽습니다.
3단계 - 배열 요소를 입력합니다.
4단계 - 포인터 변수를 선언합니다.
5단계 - 런타임에 동적으로 메모리를 할당합니다.
6단계 - 검색할 요소를 입력합니다.
7단계 - 순회하여 배열에 요소가 있는지 확인합니다. 요소가 발견되면 "예"를 표시하고 그렇지 않으면 "아니오"를 표시합니다.
예시
배열 크기:5
배열 요소는 다음과 같습니다.
1 2 3 4 5
검색할 요소를 입력하십시오:4
출력은 다음과 같습니다 -
4 is present in the array
예시
다음은 포인터를 사용하여 요소를 배열로 삭제하는 C 프로그램입니다 -
#include<stdio.h>
int i,l;
int search(int ,int *,int);
int main(){
int n,m;
printf("enter the size of array:");
scanf("%d",&n);
int a[n];
printf("enter the elements:\n");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("enter the element to be searched:");
scanf("%d",&m);
search(n,a,m);
return 0;
}
int search(int n,int *a,int m){
for(i=0;i<n;i++){
if(m==a[i]){
l=1;
break;
}
}
if(l==1){
printf("%d is present in the array",m);
} else {
printf("%d is not present in the array",m);
}
} 출력
위의 프로그램이 실행되면 다음과 같은 출력을 생성합니다 -
Run 1: enter the size of array:5 enter the elements: 14 12 11 45 23 enter the element to be searched:11 11 is present in the array Run 2: enter the size of array:3 enter the elements: 12 13 14 enter the element to be searched:45 45 is not present in the array