c语言中数组元素的线性查找。
1、再数组中查找特定的元素,并返回查找的索引。
#include <stdio.h>
#define NUMBER 7
#define FAILED -1
int func1(const int x[], int y, int z)
{
int i = 0;
while (1)
{
if (i == z)
return FAILED;
if (x[i] == y)
return i;
i++;
}
}
int main(void)
{
int i, a[NUMBER], index, key;
puts("please input the elements.");
for (i = 0; i < NUMBER; i++)
{
printf("a[%d] : ", i); scanf("%d", &a[i]);
}
printf("please input the target element for search: ");
scanf("%d", &key);
index = func1(a, key, NUMBER);
if (index == FAILED)
puts("target element no exist!");
else
printf("the order of target element is: %d\n", index + 1);
return 0;
}
该程序在数组中查找特定元素,如果存在就返回元素所在数组中的第一个索引。