习题8-2 在数组中查找指定元素 (15分)

本题要求实现一个在数组中查找指定元素的简单函数。

函数接口定义:

int search( int list[], int n, int x );
 

其中list[]是用户传入的数组;n0)是list[]中元素的个数;x是待查找的元素。如果找到

则函数search返回相应元素的最小下标(下标从0开始),否则返回1。

裁判测试程序样例:

#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
", index);
    else
        printf("Not found
");

    return 0;
}

/* 你的代码将被嵌在这里 */
 

输入样例1:

5
1 2 2 5 4
2
 

输出样例1:

index = 1
 

输入样例2:

5
1 2 2 5 4
0
 

输出样例2:

Not found


 1 int search( int list[], int n, int x ){
 2     int cnt=0;
 3     if(n==0){
 4         return -1;
 5     }
 6     else{
 7         for(int i=0;i<=n;i++){
 8             if(list[i]==x){
 9                 cnt++;
10                 return i;
11             }
12             if(cnt!=0){
13                 break;
14             }
15         }
16         if(cnt==0){
17             return -1;
18         }
19     }
20 }
原文地址:https://www.cnblogs.com/samgue/p/13218335.html