C++ Primer Plus Chapter 7 Exercise 9

c plus plusChapter 7 ends with a short exercise on function pointers. The simplest way to complete this, which I provided in my source, is to create the two functions add() and calculate(), then call them in main() with a loop. The text mentions if you are feeling adventurous to include other functions in addition to add. For simplicities sake, I did the minimum requirement here. Finally,  we can put this chapter to rest. See my source below:

9. Design a function calculate() that takes two type double values and a pointer to a function that takes two double arguments and returns a double. The calculate() function should also be type double, and it should return the value that the pointed-to function calculates, using the double arguments to calculate(). For example, suppose you have this definition for the add() function: double add(double x, double y){return x + y}. Then, the function call in double q = calculate(2.5, 10.4, add); would cause calculate() to pass the values 2.5 and 10.4 to the add() function and then return the add() return value (12.9). Use these functions and at least one additional function in the add() mold in a program. The program should use a loop that allows the user to enter pairs of numbers. For each pair, use calculate() to invoke add() and at least one other function. If you are feeling adventurous, try creating an array of pointers to add()-style functions and use a loop to successively apply calculate() to a series of functions by using these pointers. Hint: Here’s how to declare such an array of three pointers: double (*pf[3])(double, double); You can initialize such an array by using the usual array initialization syntax and function names as addresses.

#include <iostream>

using namespace std;

double calculate(double x, double y, double (*pf)(double a, double b));
double add(double x, double y);

int main()
double x, y;
cout << "Enter two numbers (q to exit): ";
while(cin >> x >> y)
calculate(x, y, add);
cout << "The sum is: " << calculate(x, y, add) << "\n\n";
return 0;

double calculate(double x, double y, double (*pf)(double a, double b))
return pf(x, y);

double add(double x, double y)
return x + y;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s