您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言读入一个数组并检索某个值是否在数组中

时间:01-03来源:作者:点击数:

下面的程序,会读入一个整数数组,并对数组中的元素进行搜索,判断给定的值是否在数组中。

#include <stdio.h>
#define NMAX 10
int getIntArray(int a[], int nmax, int sentinel);
void printIntArray(int a[], int n);
int linear(int a[], int n, int who);
int main(void) {
    int x[NMAX];
    int hmny;
    int who;
    int where;
    hmny = getIntArray(x, NMAX, 0);
    printf("The array was: \n");
    printIntArray(x,hmny);
    printf("Now we do linear searches on this data\n");
    do{
        printf("Enter integer to search for [0 to terminate] : ");
        scanf("%d", &who);
        if(who==0) break;
        where = linear(x,hmny,who);
        if (where<0){
            printf("Sorry, %d is not in the array\n",who);
        }else{
            printf("%d is at position %d\n",who,where);
        }
    }while(1);
}
// n 为数组 a 中元素的个数;数组中的值被输出,5 个每行
void printIntArray(int a[], int n)
{
    int i;
    for (i=0; i<n; ){
        printf("\t%d ", a[i++]);
        if (i%5==0)
            printf("\n");
    }
    printf("\n");
}
// 最多读取 n 个整数并存储在数组 a 中
int getIntArray(int a[], int nmax, int sentinel)
{
    int n = 0;
    int temp;
    printf("Enter integer [%d to terminate] : ", sentinel);
    do {
        scanf("%d", &temp);
        if (temp==sentinel) break;
        if (n==nmax)
            printf("array is full! Enter integer [%d to terminate] : ", sentinel);
        else
            a[n++] = temp;
    }while (1);
    return n;
}
// 对数组 a 中的元素进行搜索;如果找到返回该元素的位置,否则返回 -1
int linear(int a[], int n, int who)
{
    int lcv;
    for (lcv=0;lcv<n;lcv++)
        if(who == a[lcv])return lcv;
    return (-1);
}

可能的输出结果:

Enter integer [0 to terminate] : 12 34 56 78 90 34464 2312 464 0
The array was:
    12            34          56        78    90
    34464     2312     464
Now we do linear searches on this data
Enter integer to search for [0 to terminate] : 12
12 is at position 0
Enter integer to search for [0 to terminate] : 56
56 is at position 2
Enter integer to search for [0 to terminate] : 34232
Sorry, 34232 is not in the array
Enter integer to search for [0 to terminate] : 0
Press any key to continue
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门