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
Reading symbols from /home/sc/Documents/a.out...done.
(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.