Answer DC23

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

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

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

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


Back to Puzzle Home