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;
     }
     else
     {
        closestProximity = closestNumber - target;
     }
     
//     printf("\n%d\n", closestProximity);
     
     for (int i = 0; i < 50; i++)
     {
        if(numary[i] < target)
        {
           newProximity = target - numary[i];
        }
        else
        {
           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 6 Years Ago by peter_budo: Please do not use CODE SNIPPED for posting question. Use FORUM THREAD.

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

2.
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 6 Years Ago 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]

for(i=0;i<50;i++)
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

Comments
Sweet! +2
This article has been dead for over six months. Start a new discussion instead.