Puzzle DC23


Linear search: look for a particular element in an array

[E-10] Write a function that searches for the first instance of a target value in an integer array. Return the index of the element if it is there, or -1 if the element is not there. Here are two runs of the testing program:

   0    1    2    3    4    5    6    7    8    9
Element 7 found at index 7

   0    1    2    3    4    5    6    7    8    9
Element 99 not found

Here is a testing program. You might want to add code so that the target value comes from user input or from a command line argument:

int linearSearch( int size, int arr[], int target )
{
....
}

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( x, SIZE );
  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;
}


Answer         Next Page         Previous Page Home