This question requires the implementation of a simple function to find a specified element in an array.
Function interface definition:
int search( int list[], int n, int x );
Among them list[]
is the array passed in by the user; n
(≥0) is list[]
the number of elements in the middle; x
is the element to be searched. If found
The function search
returns the minimum index of the corresponding element (the index starts from 0), otherwise it returns −1.
Sample referee test procedure:
#include <stdio.h>
#define MAXN 10
int search( int list[], int n, int x );
int main()
{
int i, index, n, x;
int a[MAXN];
scanf("%d", &n);
for( i = 0; i < n; i++ )
scanf("%d", &a[i]);
scanf("%d", &x);
index = search( a, n, x );
if( index != -1 )
printf("index = %d\n", index);
else
printf("Not found\n");
return 0;
}
/* 你的代码将被嵌在这里 */
Input example 1:
5
1 2 2 5 4
2
Output sample 1:
index = 1
Input example 2:
5
1 2 2 5 4
0
Output sample 2:
Not found
answer:
int search( int list[], int n, int x )
{
int *p = list; //定义指针p指向list的首地址
int i; //循环变量
int index = -1; //相应元素的最小下标
/*循环遍历数组,寻找有无相应元素*/
for (i = 0; i < n; i++, p++)
{
if ( *p == x) //如果找到下标给index,退出循环
{
index = i;
break;
}
}
return index; //返回index的值给search
}