In: Computer Science
Suppose you have a list containing exactly three integer numbers. Each number could be positive, negative, or zero. Write a C program that first asks the user for each of the numbers. After that, it should determine and display the number from the list that is nearest to the positive number five (5).
Examples:
If the numbers are 0, -3, and 8, then the displayed output is
8.
If the numbers are 6, 5, and 4, then the output is 5.
If the numbers are 3, 4, and 11, then the output is 4.
If the numbers are 4, 1, 6, then it turns out that 4 and 6 are both
equidistant from 5. In this situation, the output should be the
first number checked that satisfied the criterion. For this
example, if you started on the left at 4 and proceeded to the
right, the output is 4.
CODE IN C :
#include<stdio.h>
#include<limits.h>
int main()
{
printf("Enter the elements of the list : ");
int list[3];
for(int i = 0; i < 3; i++)
{
scanf("%d", &list[i]);
}
int x; // Element to be searched for
printf("Enter the number to be searched for : ");
scanf("%d", &x);
int diff = INT_MAX; // stores the difference, initialized to the
maximum possible value
int ans = 0;
for(int i = 0; i < 3; i++)
{
if(abs(x-list[i])<diff) // if diff is greater than the diff
between the presnt value and x, update it
{
diff = abs(x-list[i]);
ans = list[i]; // stores the nearest value to x
}
}
printf("The number from the list that is closest to %d", x);
printf(" is %d", ans);
}
OUTPUT SNIPPET :
Please give an upvote if you liked my solution. Thank you :)