# Thread: find closest number in array

1. ## find closest number in array

i want to make program to find closest number in array
ex. if array elements are 2,7,78 and user types 89 then nearest element to 89 is 78 so it should print 78 but it prints 100
why?
i think program is adding 89 to 11 where 11 is minimum differnce between number and array element but program is not checking wheheather this number is present in array or not. if number is not present then i print 2*min + b but still output is 100
can someone give me code for this program? here is my code

Code:
```#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
int a[100],i,j,n,no,s[100],min,b,flag;
printf("How many no");
scanf("%d",&n);
printf("Enter elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter to search closest element");
scanf("%d",&no);
for(i=0;i<n;i++)
{
if(no<a[i])
s[i]=a[i]-no;
else
s[i]=no-a[i];}
min=s[0];
for(i=1;i<n;i++)
{
if(s[i]<min)
min=s[i]; }
b=no-min;
for(i=0;i<n;i++)
if(b==s[i])
{
flag=1;
break;
}
if(flag==1)
printf("%d",b);
else
printf("%d",2*min+b);

}```

2. First off, learn how to indent code consistently.
Code:
```#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
int a[100], i, j, n, no, s[100], min, b, flag;
printf("How many no");
scanf("%d", &n);

printf("Enter elements");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);

printf("Enter to search closest element");
scanf("%d", &no);

for (i = 0; i < n; i++) {
if (no < a[i])
s[i] = a[i] - no;
else
s[i] = no - a[i];
}

min = s[0];
for (i = 1; i < n; i++) {
if (s[i] < min)
min = s[i];
}

b = no - min;
for (i = 0; i < n; i++)
if (b == s[i]) {
flag = 1;
break;
}

if (flag == 1)
printf("%d", b);
else
printf("%d", 2 * min + b);
}```
Next, learn how to use a debugger.
For example, put a breakpoint on the final if ( flag == 1 ), and look around.
Code:
```\$ gdb -q ./a.out
(gdb) b 38
Breakpoint 1 at 0x4006f2: file bar.c, line 38.
(gdb) run
Starting program: /home/sc/Documents/a.out
How many no3
Enter elements2 7 78
Enter to search closest element89

Breakpoint 1, main () at bar.c:38
38        if (flag == 1)
(gdb) print flag
\$1 = 0
(gdb) print min
\$2 = 11
(gdb) print b
\$3 = 78```
> printf("%d", 2 * min + b);
Well duh!
min is 11 and b is 78, so sure you get 100 printed.

Perhaps you need to examine your algorithm.

FWIW, your min should be -11, that would fix it.