Home

A program to explain pointers to functions

C Programming Language 108

Program

#include <stdio.h>
#include <math.h>
#define PI 3.1415926

double y(double x)
{
    return (2 * x * x - x + 1);
}

double table(double (*f)(), double min, double max, double step)
{
    double a, value;
    for (a = 0; a < max; a += step)
    {
        value = (*f)(a);
        printf("%5.2f %10.4f\n", a, value);
    }
}

void main()
{
    printf("Table of y(x) = 2 * x * x - x + 1\n");
    table(y, 0.0, 2.0, 0.5);

    printf("Table of y(x) = cos(x)\n");
    table(cos, 0.0, PI, 0.5);

    printf("\n");
}

Result

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
Table of y(x) = cos(x)
 0.00     1.0000
 0.50     0.8776
 1.00     0.5403
 1.50     0.0707
 2.00    -0.4161
 2.50    -0.8011
 3.00    -0.9900


Last Updated on

Next Post: Rules vs Guidelines →

Comments