当前位置:网站首页>Exercise 8-2 finding a specified element in an array (15 points)

Exercise 8-2 finding a specified element in an array (15 points)

2022-06-11 22:25:00 Xiaoyan y

This problem requires the implementation of a simple function to find the specified elements in the array .

Function interface definition :

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

among list[] Is the array passed in by the user ;n(≥0) yes list[] The number of elements in ;x Is the element to be found . If you find

The function search Returns the minimum subscript of the corresponding element ( Subscript from 0 Start ), Otherwise return to −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;
}

/* Your code will be embedded here */

sample input 1:

5
1 2 2 5 4
2

sample output 1:

index = 1

sample input 2:

5
1 2 2 5 4
0

sample output 2:

Not found

int search( int list[], int n, int x ){
    int i;
    for(i=0;i<n;i++){
        if(list[i]==x){
            return i;
            break;
        }
    }
    return -1;
}

 

原网站

版权声明
本文为[Xiaoyan y]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206112218444890.html