在数组中查找指定元素

| December 4, 2007 20:08 | timmy | Via Original
输入一个正整数repeat (0输入一个正整数n (1要求定义并调用函数search(list, n, x),它的功能是在数组list中查找元素x,若找到则返回相应下标,否则返回-1。
例:括号内是说明
输入
2   (repeat=2)
3 1 2 -6 2
5 12 2 5 4 0 100
输出
index=1
Not found




#include <stdio.h>
int main( )
{
   int ri, repeat;
   int i, index, n, res, x;
   int a[10];
   int search(int list[], int n, int x);

   scanf("%d", &repeat);
   for(ri=1; ri<=repeat; ri++){
      scanf("%d", &n);
      for(i=0; i<n; i++)
         scanf("%d", &a[i]);
      scanf("%d", &x);
    res=search(a,n,x);
      if(res!=-1)
          printf("index=%d\n", res);
      else
          printf("Not found\n");
   }
}
int search(int list[], int n, int x)
{
  int i,res;
  res=-1;
  for(i=0;i<n;i++)
    if(list[i]==x){
      res=i;
      break;
    }
  return res;
}

Tags:
Program/Code » C/C++ | Comments(0) | Trackbacks(0) | Reads(299)
Add a comment
 Site URI
 Email
  Password Optional
 Nickname  *  [Register]
               

 
Emots
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
Enable HTML
Enable UBB
Enable Emots
Hidden
Remember