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);
}

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.

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

commented: Sweet! +2 +2

Very slick, Abhimanapal. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.