Showing posts with label Use of pointers to function. Show all posts
Showing posts with label Use of pointers to function. Show all posts

Use of pointers to function

Program 55) Write a program that uses a function pointer as a function arguement.
A program to print the function values over a given range of values. The printing is done by the function table by evaluating the function passed to it by the main.

With table, we declare the parameter f as a pointer to a function as follows:
                          double  (* f) () ;
The value returned bythe function is of type double. When table is called in the statement
                         table (y, 0.0, 2, 0.5) ;
we pass a pointer to the function y as the first parameter of table. Note that y is not followed by a parameter list.
During the execution of table, the statement
                                value = (* f) (a) ;
calls the function y which is pointed to by f, passing it the parameter a. Thus the function y is evaluated over the range 0.0 to 2.0 at the intervals of 0.5.
    Similarly the call
                              table (cos, 0.0, PI, 0.5) ;
passes a pointer to cos as its first parameter and therefore, the function table evaluates the value of cos over the range 0.0 to PI at the intervals of 0.5.

                                     PROGRAM

#include <math.h>
#define  PI  3.1415926
double y (double) ;
double cos (double) ;
double table (double (*f) (), double, double, double) ;

main ( )
 {
       printf ("Table of y(x) = 2 * x * x - x + 1\n\n") ;
       table (y, 0.0, 2.0, 0.5) ;
       printf ("\nTable of cos (x) \n\n") ;
       table (cos, 0.0, PI, 0.5) ;
 }
double table (double (*f) (), double min, double max, 
                                             double max, double step)
{       double a, value ;
        for (a = min; a <= max; a += step)
        {
                value  = (*f) (a) ;
                printf ("%5.2f  %10.4f\n", a, value) ;
        }
}
double y (double x)
{
           return (2 * x * x - x + 1) ;
}

Output:                Table of y (x) = 2 * x * x - x + 1
                                0.00              1.0000
                                0.50              1.0000
                                1.00              2.0000
                                1.50              4.0000
                                2.00              7.0000
                           Table of cos (x)
                                0.00              1.0000
                                0.50              0.8776
                                1.00              0.5403
                                1.50              0.0707
                                2.00             -0.4161
                                3.00             -0.9900