Sams Teach Yourself C in 21 Days

(singke) #1

  1. Before you search an array with bsearch(), what must you do?

  2. Using bsearch(), how many comparisons would be required to find an element if
    the array had 16,000 items?

  3. Using bsearch(), how many comparisons would be required to find an element if
    an array had only 10 items?

  4. Using bsearch(), how many comparisons would be required to find an element if
    an array had 2 million items?

  5. What values must a comparison function for bsearch()andqsort()return?

  6. What does bsearch()return if it can’t find an element in an array?


Exercises ........................................................................................................


  1. Write a call to bsearch(). The array to be searched is called names, and the values
    are characters. The comparison function is called comp_names(). Assume that all
    the names are the same size.
    2.BUG BUSTER:What is wrong with the following program?
    #include <stdio.h>
    #include <stdlib.h>
    int main( void )
    {
    int values[10], count, key, *ptr;
    printf(“Enter values”);
    for( ctr = 0; ctr < 10; ctr++ )
    scanf( “%d”, &values[ctr] );
    qsort(values, 10, compare_function());
    }
    3.BUG BUSTER:Is anything wrong with the following compare function?
    int intcmp( int element1, int element2)
    {
    if ( element 1 > element 2 )
    return -1;
    else if ( element 1 < element2 )
    return 1;
    else
    return 0;
    }
    Answers are not provided for the following exercises:
    4.ON YOUR OWN:Modify Listing 19.1 so that the sqrt()function works with
    negative numbers. Do this by taking the absolute value of x.


558 Day 19

30 448201x-CH19 8/13/02 11:20 AM Page 558

Free download pdf