C23 Answer


#include <stdio.h>
#include <stdlib.h>

/* Puzzle C23 -- linear search: look for an element x in an array
|
|  Return the first index at which x is found, or -1 if not found.
|
*/
int linearSearch( int arr[], int size, int x )
{
  int j;
  
  for ( j=0; j < size; j++ )
  {
    if ( arr[j] == x ) return j;
  }
  
  return -1;
}

void printArray( int arr[], int size );

int main(int argc, char *argv[])
{
  const int SIZE = 10;
  int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  int loc, target;
   
  printArray( x, SIZE );
  target = 7;
  loc = linearSearch( x, SIZE, target );
  
  if ( loc != -1 )
    printf("Element %d found at index %d\n", target, loc );
  else
    printf("Element %d not found\n", target);
    
  printf("\n");
  system("pause");	
  return 0;
}