下面的程序,会读入一个整数数组,并对数组中的元素进行搜索,判断给定的值是否在数组中。
#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);
}
可能的输出结果: