Puzzle DC25


Find the element in an array closest to a particular value

[M-15] Write a function that searches for the value in an integer array that is closest to a target value. Return the index of the element. If several elements are equally close to the target, return the index of the first one. Here is a testing program:

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

/* Puzzle D25 -- find the element in an
|                array closest to a particular value
*/
int linearSearchClosest( int size, int arr[], int target )
{
}

int main()
{
  const int SIZE = 10;
  int x[] = { -5, -3, 0, 6, 4, 16, -3, 0, 7, 9 };
  int loc, target;
  char input[32];
  
  printf("target:");
  scanf("%s", input );
  while ( strcmp( input, "q" ) != 0 )
  {
    target = atoi( input );
    loc = linearSearchClosest( x, SIZE, target );
    printf("Closest element to  %d found at index %d\n",
      target, loc );
    printf("target:");
    scanf("%s", input );
  }
  
  	
  return 0;
}

Here is sample output of the testing program. The user enters a value for the target after the prompt:

  -5   -3    0    6    4   16   -3    0    7    9
target:6
Closest element to  6 found at index 3
target:5
Closest element to  5 found at index 3
target:3
Closest element to  3 found at index 4
target:-9
Closest element to  -9 found at index 0
target:23
Closest element to  23 found at index 5
target:0
Closest element to  0 found at index 2
target:q

The testing program allows the user to enter targets. The user enters "q" to end the program.



Answer         Next Page         Previous Page Home