CS Electrical And Electronics
@cselectricalandelectronics

Introduce 1D Array manipulation and implement Binary search

All QuestionsCategory: C LanguageIntroduce 1D Array manipulation and implement Binary search
nikhil.d asked 3 years ago
2 Answers
nikhil.d answered 3 years ago

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
    int n, i, low, mid, high;
    char a[20][20], key[20];
    printf(“Enter the number of names\n”);
    scanf(“%d”, &n);
    printf(“Enter the names\n”);
    for (i = 0; i < n; i++)
    {
        scanf(“%s”, a[i]);
    }
    printf(“Enter the key\n”);
    scanf(“%s”, key);
    low = 0;
    high = n – 1;
    while (low <= high)
    {
        mid = (high + low) / 2;
        if (strcmp(a[mid], key) == 0)
        {
            printf(“Name found at %d\n”, mid + 1);
            exit(0);
        }
        else if (strcmp(a[mid], key) > 0)
            high = mid – 1;
        else
            low = mid + 1;
    }
    printf(“Unsuccessful search \n”);
}

Anonymous answered 3 years ago

Note: Change the double inverted comma ( ” ) in the code to avoid an error.