Implementing Binary search in the iterative procedure. Searching 3 values one by one, the first one which will be placed in low and mid-index, 2nd one which will be placed in the mid and high index and the last one value will be the highest value of your array and will not be found.
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter first value to find\n");
scanf("%d", &search);
printf("Enter second value to find\n");
scanf("%d", &search);
printf("Enter third value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}
The correct way is to put code that should be repeated for different values either in a loop or in a function. Here you could easily use a loop:
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
const char* label[] = { "first", "second", "third" };
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
// idiomatic way for an array length
unsigned repeat = sizeof(label) / sizeof(*label);
for (unsigned count = 0; count < repeat; count++) {
printf("Enter %s value to find\n", label[count]);
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first + last) / 2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle + 1);
break;
}
else
last = middle - 1;
middle = (first + last) / 2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
}
return 0;
}
But you should always control the return value of an input function (scanf
): if you type a non numeric character (e.g. an a
) all the following scanf
will return 0
instead of 1 and leave the variable untouched. Your code will then use uninitialized value which invokes Undefined Behaviour (the hell for C programmers...).
All your scanf
calls should look like:
if (1 != scanf("%d", &n)) {
// process error
fprintf(stderr, "Incorrect input\n");
exit(1);
}
You will stop the program in an ordered way and warn the user for the reason instead of risking a crash or unexpected results with no error message.