Linear Search

Source Code in C

 1: Linear Search
 2: #include <stdio.h>
 3: #include <stdlib.h>
 4: 
 5: void seiriaki_anazitisi(int pinakas[],int megethos,int arithmos,int *plithos_sygriseon
 6:                                ,int *thesi_pinaka,int *vrethike);
 7:  
 8: int main()
 9: {
 10:  int n;
 11:  int vrethike;
 12:  int plithos;
 13:  int thesi;
 14:  int k;
 15:  int i;
 16:  int *x;
 17:  printf("dose to megethos tou pinaka:");
 18:  scanf("%d",&n);
 19:  x=(int*)malloc(n*sizeof(int));
 20:  printf("dose ta stoixeia tou taksinomimenou pinaka:\n");
 21:  i=0;
 22:  while(i<n)
 23:  {
 24:   printf("x[%d]=",i);
 25:   scanf("%d",&x[i]);
 26:   i++;
 27:  }
 28:  printf("dose enan arithmo:");
 29:  scanf("%d",&k);
 30:  plithos=0;
 31:  thesi=0;
 32:  seiriaki_anazitisi(x,n,k,&plithos,&thesi,&vrethike);
 33:  if(vrethike!=0)
 34:    {
 35:      printf("o arithmos yparxei ston pinaka");
 36:      printf("\no arithmos yparxei stin thesi %d",thesi);
 37:      printf("\nto plithos sygriseon pou eginan einai:%d",plithos);
 38:    }
 39:  else
 40:   if(vrethike==0)
 41:   {
 42:    printf("o arithmos den yparxei");
 43:    printf("\nto plithos sygriseon pou eginan einai:%d",plithos);
 44:   }
 45:  
 46:  return 0;
 47: } 
 48: 
 49:  
 50: void seiriaki_anazitisi(int pinakas[],int megethos,int arithmos,int *plithos_sygriseon
 51:                                ,int *thesi_pinaka,int *vrethike)
 52: {
 53:   int i;
 54:   *vrethike=0;   /*Den exei brethei o arithmos*/
 55:   *plithos_sygriseon=0;
 56:   *thesi_pinaka=-1;
 57:   for(i=0;i<megethos;i++)
 58:   {
 59:     (*plithos_sygriseon)++;
 60:     if(arithmos<pinakas[i]) /*Den yparxei o arithmos ston pinaka*/
 61:       break;
 62:     else
 63:     {
 64:       if(arithmos==pinakas[i])
 65:       {
 66:         *thesi_pinaka=i;
 67:         *vrethike=1;
 68:         break;
 69:       }
 70:     }
 71:   }
 72: }