Home Tutorial C bsearch() function in C

 
 

Share on Google+Share on Google+
bsearch() function in C
Posted on: December 26, 2009 at 12:00 AM
Advertisement
This section demonstrates the use bsearch()function in C Language.

bsearch() function in C Programming Language

This section demonstrates the use bsearch() function in C. This searches function the given key in the array pointed by base. Here we are going to search a particular character from the character array. To perform the search, the bsearch() function compares the elements of the specified array to the key by calling the function comp(). This function must accept two parameters that are pointers to elements, type-casted as void* and compare their values which returns the result of the subtraction of the values pointed by both.

If the values are equal, it will return 0,
If the value pointed by a is greater than the b, it will return 1,
If the value pointed by b is greater than the a, it will return -1.

In the main function, user is allowed to input the character to search and call to bsearch() function with input character as a key. It will search that key in the array of values whether it is there or not.

Here is the code:

#include <stdlib.h>
#include
<ctype.h>
#include <stdio.h>
#include
<conio.h>

char charr[] = { 'a', 'b', 'c', 'd' };
int
comp(const void *a, const void *b);
int main(void) {
        char ch;
        char *p;
        printf("Enter a character: ");
        ch = getchar();
        ch = tolower(ch);
        p = (char *) bsearch(&ch, charr, 4, 1, comp);
        if (p)
           printf(" %c is in the Array\n", *p);
        else
           printf(" %c is not in the Array\n");
        getch();
        return 0;
        }
int
comp(const void *a, const void *b) {
        return *(char *) a - *(char *) b;
}

Output:

Enter a character: h
h is not in the Array

Enter a character: a
a is in the Array

Advertisement

Related Tags for bsearch() function in C:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 26, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com