C Exercises: Check which number nearest to the value 100 among two given integers
10. Nearest to 100
Write a C program to check which number is nearest to the value 100 among two given integers. Return 0 if the two numbers are equal.
C Code:
Sample Output:
95 0 99
Explanation:
int test(int x, int y) { int n = 100; int val = abs(x - n); int val2 = abs(y - n); return val == val2 ? 0 : (val < val2 ? x : y); }
The above function initializes an integer ‘n’ with a value of 100. Then it initializes two integer variables val and val2 with the absolute difference between ‘x’ and ‘n’ and ‘y’ and ‘n’, respectively.
Next, the function checks if ‘val’ is equal to ‘val2’. If it is, then the function returns 0. Otherwise, the function checks which of the two values ‘val’ and ‘val2’ is smaller. If ‘val’ is smaller, then the function returns ‘x’. If ‘val2’ is smaller, then the function returns ‘y’.
Time complexity and space complexity:
Time complexity: The time complexity of this function is O(1) since the operations performed are simple arithmetic operations and a few conditional statements, and the number of operations is constant regardless of the input size.
Space complexity: The space complexity of this function is O(1) since the function only uses a fixed number of integer variables and does not create any data structures or arrays.
Pictorial Presentation:
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C program that determines which of two numbers is closest to 50, returning 0 if both are equally close.
- Write a C program to find the number nearest to a given target value, with a twist: if both are equal, return -1.
- Write a C program to compare two numbers and return the one closest to a user-defined target, except when both numbers differ by less than 2, then return the sum.
- Write a C program that checks two integers and returns the one that is nearest to 200; if equidistant, return the product of the numbers.
C Programming Code Editor:
Previous: Write a C program to check whether two given integer values are in the range 20..50 inclusive. Return true if 1 or other is in the said range otherwise false.
Next: Write a C program to check whether two given integers are in the range 40..50 inclusive, or they are both in the range 50..60 inclusive.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.