Hi I'm writing a menu driven array with 50 randomly generated integers. In the program I am suppose to search for numbers in the array and print the number and location of the number in the array. I have most of the program finished, however when I input an incorrect integer to find in the array I also need to show that the number is incorrect and the greatest number less than the target (w/ index location) and the smallest value greater than the target (w/ index location).

So far I've written a function where it finds just the next closest number to the target but I don't know how to change it so that it can differentiate between the greatest number less than target and smallest number greater than target.

void checkNum(int numary[], int target)
     int closestNumber = 0;
     int closestProximity = 0;
     int newProximity = 0;
     int location = 0;
     closestNumber = numary[0];
     if (closestNumber < target)
        closestProximity = target - closestNumber;
        closestProximity = closestNumber - target;
//     printf("\n%d\n", closestProximity);
     for (int i = 0; i < 50; i++)
        if(numary[i] < target)
           newProximity = target - numary[i];
           newProximity = numary[i] - target;
        if (newProximity < closestProximity)
           closestProximity = newProximity;
           closestNumber = numary[i];
           location = i;
      printf("\nClosest Value Before: %d at location %d", closestNumber, location); 
//      printf("\nCloset Value After: %d at location %d", closestNumberA, locationA);

Edited by peter_budo: Please do not use CODE SNIPPED for posting question. Use FORUM THREAD.

7 Years
Discussion Span
Last Post by abhimanipal

You have 2 options:
Sort the array, then search. If done properly, the numbers you're looking for will be directly adjacent to the target.

Use 2 double tests to check if a value falls within an ever-changing range of values.

if (nextLow < input && input < target) {
 /* do something */
// and...
if (nextHigh > input && input > target) {
  /* do something else */

The rest is up to you.

Edited by Fbody: n/a


i have to be able to search the array in both situations an unsorted array and a sorted array

i also understand that i need to do two tests however i don't understand how i would find the next highest and next lowest in the test


The logic that I would use for this problem will be as follows :

Input Array A[50]:
Temp Array B[50]

B= A - target

Sweep thru B and find the greatest -ve number and the smallest positive number . Let the indexes of these values be i1 and i2
A[i1] is the greatest number less than the target. A[i2] is the smallest number greater than the target

Votes + Comments
Sweet! +2
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.