编写函数遍历查找数组中量并输出位置
此程序,我定义变量key,length和数组a,key为要查找的数,length为数组中所容纳个数(我们用sizeof()函数实现)。
search函数使用for对数组a进行遍历,ret为返回参数。
#include <stdio.h>
int search(int key, int a[], int length);
int main()
{
int a[]={1,25,62,45,87,23,41,12,17,16,},key,loc;
printf("input your key number:");
scanf("%d", &key);
loc = search(key, a, (sizeof(a) / sizeof(a[0])));
if(loc!=-1)
{
printf("the key location is :%d\n", loc);
}else
printf("the key not found!\n");
return 0;
}
int search(int key,int a[],int length)
{
int ret = -1;
for (int i = 0; i < length;i++)
{
if(key==a[i])
{
ret = i;
break;
}
}
return ret;
}
输出结果
