[c언어] 배열에서 key 값 찾기
2020. 12. 16. 11:27ㆍComputer Science/C
배열 a안에 searchKey 값이 있는가를 탐색하여 해당 첨자를 반환한다.
searchKey값이 없는 경우는 -1을 반환한다.
#include <stdio.h>
int indexSearch(int a[], int size, int searchKey);
#define SIZE 12
int main(void)
{
int incomes[12] = { 11,22,33,44,55,66,11,22,33,44,55,66 };
int income, id;
printf("탐색할 수입은? ");
scanf("%d", &income);
id = indexSearch(incomes, SIZE, income);
if (id == -1)
printf("수입 %d를 갖는 달은 없습니다.\n", income);
else
printf("수입 %d를 갖는 첫번째 달은 %d월 입니다.\n", income, id + 1);
return 0;
}
int indexSearch(int a[], int size, int searchKey)
{
int i;
for (i = 0;i < size;i++)
{
if (a[i] == searchKey)
return i;
}
return -1;
}
결과
'Computer Science > C' 카테고리의 다른 글
[c언어] 자리예약 시스템 (0) | 2020.12.21 |
---|---|
[c언어] 4칙 연산 (switch문) (0) | 2020.12.16 |
[c언어] 단어 점수 계산 (1) | 2020.12.16 |
[c언어] 단어 안에 포함된 숫자 합 구하기 (0) | 2020.12.16 |
[c언어] 같은 단어 판별하기 (0) | 2020.12.16 |