Home

Pointers and Functions

 

Pointers to Functions

 

Introduction

Imagine you are writing a program to process cylinder-related calculations, that is, to get its diameter, its circumference, its areas, and volume. The formulas used are reviewed in our Geometric Formulas section. You could start your program as follows:

#include <iostream>
using namespace std;

int main()
{
    double Radius;

    Radius = 25.55;

    cout << "Cylinder Summary";
    cout << "\nRadius:   " << Radius;

    return 0;
}

This would produce:

Cylinder Summary
Radius:   25.55
Press any key to continue...

When we studied functions that return a value, we saw that the result of such a function can be assigned to a value locally declared in the calling function:

#include <iostream>
using namespace std;

int main()
{
    double Radius, Diameter;
    double CalculateDiameter(double R);

    Radius = 25.52;

    Diameter = CalculateDiameter(Radius);

    cout << "Cylinder Summary";
    cout << "\nRadius:   " << Radius;
    cout << "\nDiameter: " << Diameter;

    return 0;
}

double CalculateDiameter(double Rad)
{
    return Rad * 2;
}

At this time, we know that when a function returns a value, the calling of the function is a complete value that can be assigned to a variable. In fact, when calling a function that takes an argument, if that argument itself is gotten from a value returned by a function, the calling of the second function can be done directly when calling the first function. This seemingly complicated scenario can be easily demonstrated as follows:

#include <iostream>
using namespace std;

int main()
{
    double Radius, Circumference;
    double CalculateDiameter(double R);
    double CalculateCircumference(double D);

    Radius = 25.52;

    // Instead of calling the CalculateDiameter() function first and
    // assign it to another, locally declared variable, such as in
    // "double Diameter = CalculateDiameter(Radius)", we can call the
    // CalculateDiameter(Radius) directly when we are calling the
    // CalculateCircumference() function.
    // This is possible because the CalculateCircumference() function
    // takes an argument that is the result of calling the
    // CalculateDiameter() function. As long as we only need the
    // circumference and we don't need the diameter, we don't have
    // to explicitly call the CalculateDiameter() function.

    Circumference = CalculateCircumference(CalculateDiameter(Radius));

    cout << "Cylinder Summary";
    cout << "\nRadius:   " << Radius;
    cout << "\nCircumference: " << Circumference << endl;

    return 0;
}

double CalculateDiameter(double Rad)
{
    return Rad * 2;
}

double CalculateCircumference(double Diam)
{
    const double PI = 3.14159;
    return Diam * PI;
}

In some circumstances, such as this one, we may find out that the value we want to process in a function is in fact a value gotten from an intermediary function. Unfortunately, a regular function cannot be passed to a function like a regular variable. In reality, the C++ language allows this but the function must be passed as a pointer.

Practical LearningPractical Learning: Reviewing Functions

A loan is the amount of money a person or a company would borrow from another person or another company. There are various calculations involved in loan-related calculations. For example, when you borrow money from a bank, the bank applies a percentage of the amount you would pay each period of time which could be a few days, each month, each quarter, at the end of a year or after a few years. Whether you pay monthly or on another period, there is a total amount that the loan would have cost you at the end. In this and some other subsequent sections, we will review a few ways of processing loans.

  1. Create a new C++ project named LoanProcessing1
  2. Create a new source file named Main.cpp
  3. Change the Main.cpp file as follows:
     
    #include <iostream>
    using namespace std;
    
    double GetPrincipal();
    double GetInterestRate();
    double GetPeriod();
    
    int main()
    {
        double Principal, IntRate;
        int    NumberOfPeriods;
    
        cout << "This program allows you to calculate the amount of money a "
             << "customer will owe at the end of the lifetime of a loan\n";
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
        cout << "\nLoan Processing\n";
        Principal      = GetPrincipal();
        IntRate        = GetInterestRate();
        NumberOfPeriods= GetPeriod();
        
        cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
        cout << "\n==================================";
        cout << "\nEstimate on loan";
        cout << "\n----------------------------------";
        cout << "\nPrincipal: $" << Principal;
        cout << "\nInterest:   " << IntRate << "%";
        cout << "\nPeriod:     " << NumberOfPeriods << " Months";
        cout << "\n==================================\n";
    
        return 0;
    }
    
    double GetPrincipal()
    {
        double P;
    
        cout << "Enter the Principal: $"; cin >> P;
    
        return P;
    }
    
    double GetInterestRate()
    {
        double r;
    
        cout << "Enter the Interest Rate (%): "; cin >> r;
    
        return r;
    }
    
    double GetPeriod()
    {
        double t;
    
        cout << "Enter the number of months: "; cin >> t;
    
        return t;
    
    }
  4. Test the application. Here is an example:
     
    This program allows you to calculate the amount of money a customer will owe at
    the end of the lifetime of a loan
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Loan Processing
    Enter the Principal: $750
    Enter the Interest Rate (%): 11.25
    Enter the number of months: 8
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    ==================================
    Estimate on loan
    ----------------------------------
    Principal: $750
    Interest:   11.25%
    Period:     8 Months
    ==================================
    Press any key to continue...
  5. Return to your programming environment
  6. In the above program, the clerk was asked to provide the number of months for the period of the loan. Depending on the loan, one customer may want to specify the number of days necessary to pay the loan. Another customer may want to pay a loan over a number of years. To make this possible, we will allow the clerk to select the type of period for a loan.
    Change the Main.cpp file as follows:
     
    #include <iostream>
    using namespace std;
    
    double GetPrincipal();
    double GetInterestRate();
    double GetPeriod(int &PeriodType, double &NumberOfPeriods);
    
    int main()
    {
        double Principal, IntRate;
        int    TypeOfPeriod;
        int    Periods;
        string PeriodName;
    
        cout << "This program allows you to calculate the amount of money a "
             << "customer will owe at the end of the lifetime of a loan\n";
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
        cout << "\nLoan Processing\n";
        Principal      = GetPrincipal();
        IntRate        = GetInterestRate();
    
        GetPeriod(TypeOfPeriod, Periods);
        if( TypeOfPeriod == 0 )
        {
            // Since the user made a bad selection, stop the program here
            cout << "Press any key to stop...";
    
            return 0;
    
        }   // Since this "if" condition has a "return 0" line, if the "if"
            // condition produces true, the "return 0" means the function
            // would be terminated. If the condition is false, the inside of
            // this "if" condition would not execute and the function would
            // continue. This means that, if the condition is false, then
            // the "else' is implied. Therefore, we don't have to write an
            // "else" condition: it is automatic.
    
        if( TypeOfPeriod == 1 )
        {
            PeriodName = " Days";
        }
        else if( TypeOfPeriod == 2 )
        {
            PeriodName = " Months";
        }
        else if( TypeOfPeriod == 3 )
        {
            PeriodName = " Years";
        }
    
        cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
    
        cout << "\n==================================";
        cout << "\nEstimate on loan";
        cout << "\n----------------------------------";
        cout << "\nPrincipal: $" << Principal;
        cout << "\nInterest:   " << IntRate << "%";
        cout << "\nPeriod:     " << Periods << PeriodName;
    
        cout << "\n==================================\n";
    
        return 0;
    }
    
    double GetPrincipal()
    {
        double P;
    
        cout << "Enter the Principal: $"; cin >> P;
    
        return P;
    }
    
    double GetInterestRate()
    {
        double r;
    
        cout << "Enter the Interest Rate (%): "; cin >> r;
    
        return r;
    }
    
    void GetPeriod(int &TypeOfPeriod, int &Periods)
    {
        cout << "How do you want to enter the length of time?";
        cout << "\n1 - In Days";
        cout << "\n2 - In Months";
        cout << "\n3 - In Years";
        cout << "\nYour Choice: "; cin >> TypeOfPeriod;
    
        if( TypeOfPeriod == 1 )
        {
            cout << "Enter the number of days: ";   cin >> Periods;
        }
        else if( TypeOfPeriod == 2 )
        {
            cout << "Enter the number of months: "; cin >> Periods;
        }
        else if( TypeOfPeriod == 3 )
        {
            cout << "Enter the number of years: ";  cin >> Periods;
        }
        else
        {
            TypeOfPeriod = 0;
            // The user made an invalid selection. So, we will give up
    
            cout << "\nBad Selection\n";
        }
    }
  7. Test the application. Here is an example:
     
    This program allows you to calculate the amount of money a customer will owe at
    the end of the lifetime of a loan
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Loan Processing
    Enter the Principal: $1500
    Enter the Interest Rate (%): 10.75
    How do you want to enter the length of time?
    1 - In Days
    2 - In Months
    3 - In Years
    Your Choice: 3
    Enter the number of years: 2
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    ==================================
    Estimate on loan
    ----------------------------------
    Principal: $1500
    Interest:   10.75%
    Period:     2 Years
    ==================================
    
    Press any key to continue...
  8. Test the program again, making a different selection for the period. Here is an example:
     
    This program allows you to calculate the amount of money a customer will owe at
    the end of the lifetime of a loan
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Loan Processing
    Enter the Principal: $650
    Enter the Interest Rate (%): 14.25
    How do you want to enter the length of time?
    1 - In Days
    2 - In Months
    3 - In Years
    Your Choice: 8
    
    Bad Selection
    Press any key to stop...
  9. Return to your programming environment
  10. Create a new unit and save it as Loan
  11. In the Loan.h file, create the following namespace and  function:
     
    #ifndef LoanH
    
    #define LoanH
    
    
    
    namespace Finance
    
    {
    
    double InterestAmount(double P, double r, double t);
    
    }
    
    
    
    #endif
  12. In the Loan.cpp file, implement the function as follows:
     
    #include "Loan.h"
    
    
    
    namespace Finance
    
    {
    
    // Interest = Principal * rate * time in years
    
    double InterestAmount(double P, double r, double t)
    
    {
    
        return P * (r / 100) * t;
    
    }
    
    }
  13. To prepare a test of the function, change the Main.cpp as follows:
     
    #include <iostream>
    
    #include "Loan.h"
    
    using namespace std;
    
    
    
    double GetPrincipal();
    
    double GetInterestRate();
    
    double GetPeriod(int &PeriodType, double &NumberOfPeriods);
    
    
    
    int main()
    
    {
    
        double Principal, IntRate, Period, InterestAmount;
    
        int    TypeOfPeriod;
    
        double Periods;
    
        string PeriodName;
    
    
    
        cout << "This program allows you to calculate the amount of money a "
    
             << "customer will owe at the end of the lifetime of a loan\n";
    
    
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
    
        cout << "\nLoan Processing\n";
    
        Principal      = GetPrincipal();
    
        IntRate        = GetInterestRate();
    
        Period         = GetPeriod(TypeOfPeriod, Periods);
    
        InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);
    
    
    
        if( TypeOfPeriod == 0 )
    
        {
    
            // Since the user made a bad selection, stop the program here
    
            cout << "Press any key to stop...";
    
            
    
            return 0;
    
        }
    
    
    
        if( TypeOfPeriod == 1 )
    
        {
    
            PeriodName = " Days";
    
        }
    
        else if( TypeOfPeriod == 2 )
    
        {
    
            PeriodName = " Months";
    
        }
    
        else if( TypeOfPeriod == 3 )
    
        {
    
            PeriodName = " Years";
    
        }
    
    
    
        cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
    
        cout << "\n==================================";
    
        cout << "\nEstimate on loan";
    
        cout << "\n----------------------------------";
    
        cout << "\nPrincipal: $" << Principal;
    
        cout << "\nInterest:   " << IntRate << "%";
    
        cout << "\nPeriod:     " << Periods << PeriodName;  
    
        cout << "\n--------------------------------";
    
        cout << "\nInterest paid on Loan: $" << InterestAmount;
    
        cout << "\n==================================\n";
    
        
    
        return 0;
    
    }
    
    
    
    double GetPrincipal()
    
    {
    
        double P;
    
    
    
        cout << "Enter the Principal: $"; cin >> P;
    
        return P;
    
    }
    
    
    
    double GetInterestRate()
    
    {
    
        double r;
    
    
    
        cout << "Enter the Interest Rate (%): "; cin >> r;
    
        return r;
    
    }
    
    
    
    double GetPeriod(int &TypeOfPeriod, double &Periods)
    
    {
    
        cout << "How do you want to enter the length of time?";
    
        cout << "\n1 - In Days";
    
        cout << "\n2 - In Months";
    
        cout << "\n3 - In Years";
    
        cout << "\nYour Choice: "; cin >> TypeOfPeriod;
    
    
    
        if( TypeOfPeriod == 1 )
    
        {
    
            cout << "Enter the number of days: "; cin >> Periods;
    
            return Periods / 360;
    
        }
    
        else if( TypeOfPeriod == 2 )
    
        {
    
            cout << "Enter the number of months: "; cin >> Periods;
    
            return Periods / 12;
    
        }
    
        else if( TypeOfPeriod == 3 )
    
        {
    
            cout << "Enter the number of years: "; cin >> Periods;
    
            return Periods;
    
        }
    
        else
    
        {
    
            TypeOfPeriod = 0;
    
            // The user made an invalid selection. So, we will give up
    
            cout << "\nBad Selection\n";
    
            return 0.00;
    
        }
    
    }
  14. Test the program. Here is an example:
     
    This program allows you to calculate the amount of money a customer will owe at
    
    the end of the lifetime of a loan
    
    
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    Loan Processing
    
    Enter the Principal: $650
    
    Enter the Interest Rate (%): 10.25
    
    How do you want to enter the length of time?
    
    1 - In Days
    
    2 - In Months
    
    3 - In Years
    
    Your Choice: 1
    
    Enter the number of days: 120
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    
    
    ==================================
    
    Estimate on loan
    
    ----------------------------------
    
    Principal: $650
    
    Interest:   10.25%
    
    Period:     120 Days
    
    --------------------------------
    
    Interest paid on Loan: $22.2083
    
    ==================================
    
    
    
    Press any key to continue...
  15. Return to your programming environment

Declaring a Pointer to Function

A pointer to a function is a function that is declared as a pointer. Its name by itself is considered a variable. As such, and unlike a regular variable, the name of this function can be assigned a regular function. This allows the function to be passed as argument. The function itself is not implemented but its name is used as a programmer type-defined object.

The reason a function can be passed as argument is because the name of a function is itself a constant pointer. The basic syntax to declare a pointer to a function is:

DataType (*FunctionName)();

The DataType can be any of the data types we have used so far and objects we will learn in future lessons.

The FunctionName must be a valid name for a function. The name of the function must be preceded by an asterisk operator. To actually make this declaration a pointer to a function, the asterisk and the name of the pointer must be included between parentheses. If you omit the parentheses, the compiler would think that you are declaring a function that would return a pointer, which changes everything.

Because this is a pointer, you must use parentheses, required for every function declared. If this function will not take any argument, you can leave the parentheses empty or type void.

Based on this, you can declare a pointer to a function as follows:

#include <iostream>

using namespace std;



int main()

{

    void (*SomethingToDo)(void);

    

    return 0;

}
 
 

After declaring a pointer to a function, keep in mind that this declaration only creates a pointer, not an actual function. In order to use it, you must define the actual function that would carry the assignment the function is supposed to perform. That function must have the same return type and the same (number of) argument(s), if any. For example, the above declared pointer to function is of  type void and it does not take any argument. you can define a function as follows:

void MovieQuote()

{

    cout << "We went through a lot of trouble because of you\n";

    cout << "You owe us\n";

    cout << "\tFrom \"Disorganized Crime\"\n";

}

With such an associated function defined, you can assign it to the name of the pointer to function as follows

SomethingTodo = MovieQuote;

This assignment gives life to the function declared as pointer. The function can then be called as if it had actually been defined. Here is an example:

#include <iostream>

using namespace std;



void MovieQuote()

{

    cout << "We went through a lot of trouble because of you\n";

    cout << "You owe us\n";

    cout << "  From \"Disorganized Crime\"\n";

}



int main()

{

    void (*SomethingToDo)();



    // Assign the MovieQuote() function to the pointer to function

    SomethingToDo = MovieQuote;



    // Call the pointer to function as if it had been defined already

    SomethingToDo();

    

    return 0;

}

This would produce:

We went through a lot of trouble because of you

You owe us

  From "Disorganized Crime"

You can also type the keyword between the return type and the opening parenthesis.

You can also declare a pointer to function for a function that returns a value. Remember that both functions must return the same type of value (they must have the same signature). Here is an example:

#include <iostream>

using namespace std;



int Addition()

{

    int a = 16, b = 442;

    return a + b;

}



int main()

{

    int (*SomeNumber)();



    // Assign the MovieQuote() function to the pointer to function

    SomeNumber = Addition;



    // Call the pointer to function as if it had been defined already

    cout << "The number is " << SomeNumber();

    

    return 0;

}

If you want to use a function that takes arguments, when declaring the pointer to function, provide the return type and an optional name for each argument. Here is an example:

int (*SomeNumber)(int x, int y);

When defining the associated function, besides returning the same type of value, make sure that the function takes the same number and type(s) of arguments. Here is an example:

#include <iostream>

using namespace std;



int Addition(int a, int b)

{

    return a + b;

}



int main()

{

    int (*SomeNumber)(int x, int y);

    int x = 128, y = 5055;



    // Assign the MovieQuote() function to the pointer to function

    SomeNumber = Addition;



    // Call the pointer to function as if it had been defined already

    cout << x << " + " << y << " = " << SomeNumber(x, y);

    

    return 0;

}

You can also create a programmer-defined type as a pointer to function. Here is the syntax to use:

typedef (*TypeName)(Arguments);

The typedef keyword must be used.

The TypeName and its asterisk must be enclosed in parentheses. The name must follow the rules applied to objects so far.

The TypeName must be followed by parentheses. If the pointer to function will take arguments, provide its type or their types between parentheses. Otherwise, you can leave the parentheses empty (but you must provide the parentheses).

After creating such a custom type, the name of the type would be used as an alias to a pointer to function. Consequently, it can be used to declare a pointer to function. Here is an example:

#include <iostream>

using namespace std;



int Addition(int a, int b)

{

    return a + b;

}



int main()

{

    // Creating a programmer-defined type

    typedef int (*AddTwoIntegers)(int x, int y);

    // Now, the AddsTwoIntegers name is a pointer to function

    // that can take two integers. It can be used for a declaration



    AddTwoIntegers TwoNumbers;

    int x = 128, y = 5055;



    TwoNumbers = Addition;



    // Call the pointer to function as if it had been defined already

    cout << x << " + " << y << " = " << TwoNumbers(x, y);

    

    return 0;

}

This would produce:

128 + 5055 = 5183

Press any key to continue...

Practical Learning Practical Learning: Using a Pointer to Function

  1. To declare and use a pointer to function, change the Main.cpp file as follows:
     
    #include <iostream>
    
    using namespace std;
    
    
    
    #include "Loan.h"
    
    
    
    double GetPrincipal();
    
    double GetInterestRate();
    
    double GetPeriod(int &PeriodType, double &NumberOfPeriods);
    
    double Addition(double Value1, double Value2)
    
    {
    
        return Value1 + Value2;
    
    }
    
    
    
    int main()
    
    {
    
        double (*AddValues)(double R, double T);
    
    
    
        double Principal, IntRate, Period, InterestAmount;
    
        int    TypeOfPeriod;
    
        double Periods;
    
        string PeriodName;
    
    
    
        cout << "This program allows you to calculate the amount of money a "
    
             << "customer will owe at the end of the lifetime of a loan\n";
    
    
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
    
        cout << "\nLoan Processing\n";
    
        Principal      = GetPrincipal();
    
        IntRate        = GetInterestRate();
    
        Period         = GetPeriod(TypeOfPeriod, Periods); 
    
        AddValues      = Addition;
    
        InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);
    
        double Amount  = AddValues(Principal, InterestAmount);
    
    
    
        if( TypeOfPeriod == 0 )
    
        {
    
            // Since the user made a bad selection, stop the program here
    
            cout << "Press any key to stop...";
    
            
    
            return 0;
    
        }
    
    
    
        if( TypeOfPeriod == 1 )
    
        {
    
            PeriodName = " Days";
    
        }
    
        else if( TypeOfPeriod == 2 )
    
        {
    
            PeriodName = " Months";
    
        }
    
        else if( TypeOfPeriod == 3 )
    
        {
    
            PeriodName = " Years";
    
        }
    
    
    
        cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
    
        cout << "\n==================================";
    
        cout << "\nEstimate on loan";
    
        cout << "\n----------------------------------";
    
        cout << "\nPrincipal: $" << Principal;
    
        cout << "\nInterest:   " << IntRate << "%";
    
        cout << "\nPeriod:     " << Periods << PeriodName;  
    
        cout << "\n--------------------------------";
    
        cout << "\nInterest paid on Loan: $" << InterestAmount;
    
        cout << "\nTotal Amount Paid:     $" << Amount;
    
        cout << "\n==================================\n";
    
        
    
        return 0;
    
    }
    
    
    
    . . . No Change
    
    
  2. Test the program. Here is an example:
     
    This program allows you to calculate the amount of money a customer will owe at
    
    the end of the lifetime of a loan
    
    
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    Loan Processing
    
    Enter the Principal: $1500
    
    Enter the Interest Rate (%): 12.55
    
    How do you want to enter the length of time?
    
    1 - In Days
    
    2 - In Months
    
    3 - In Years
    
    Your Choice: 3
    
    Enter the number of years: 2
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    
    
    ==================================
    
    Estimate on loan
    
    ----------------------------------
    
    Principal: $1500
    
    Interest:   12.55%
    
    Period:     2 Years
    
    --------------------------------
    
    Interest paid on Loan: $376.5
    
    Total Amount Paid:     $1876.5
    
    ==================================
    
    
    
    Press any key to continue...
  3. Return to your programming environment
  4. To create a programmer-define type based on the AddValues pointer to function name, click the Loan.h tab and create the type as follows:
     
    
    #ifndef LoanH
    
    #define LoanH
    
    
    
    namespace Finance
    
    {
    
    typedef double (*Add)(double R, double T);
    
    
    
    double InterestAmount(double P, double r, double t);
    
    }
    
    
    
    #endif
  5. To declare and use a variable of the new defined type, change the Main.cpp file as follows:
     
    
    #include <iostream>
    
    
    
    using namespace std;
    
    
    
    #include "Loan.h"
    
    
    
    
    
    
    
    double GetPrincipal();
    
    double GetInterestRate();
    
    double GetPeriod(int &PeriodType, double &NumberOfPeriods);
    
    double Addition(double Value1, double Value2)
    
    {
    
        return Value1 + Value2;
    
    }
    
    
    
    int main()
    
    {
    
        Finance::Add Plus;
    
        double Principal, IntRate, Period, InterestAmount;
    
        int    TypeOfPeriod;
    
        double Periods;
    
        string PeriodName;
    
    
    
        cout << "This program allows you to calculate the amount of money a "
    
             << "customer will owe at the end of the lifetime of a loan\n";
    
    
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
    
        cout << "\nLoan Processing\n";
    
        Principal      = GetPrincipal();
    
        IntRate        = GetInterestRate();
    
        Period         = GetPeriod(TypeOfPeriod, Periods); 
    
        Plus           = TotalAmount;
    
        InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);
    
        double Amount  = Plus(Principal, InterestAmount);
    
    
    
        if( TypeOfPeriod == 0 )
    
        {
    
            // Since the user made a bad selection, stop the program here
    
            cout << "Press any key to stop...";
    
            
    
            return 0;
    
        }
    
    
    
        . . . No Change
    
        
    
        
    
        
    
        return 0;
    
    }
    
    
    
    . . .
    
    
  6. Test the application and return to your programming environment
  7. To expand the Loan unit, we will add other types to perform all four arithmetic operations used to assist the functions that will be called to perform the calculations.
    In the Loan.h file, create the following programmer-defined types:
     
    
    #ifndef LoanH
    
    #define LoanH
    
    
    
    namespace Finance
    
    {
    
    typedef double (*Add)(double R, double T);
    
    typedef double (*Subtract)(double First, double Second);
    
    typedef double (*Multiply)(double First, double Second);
    
    typedef double (*Divide)(double First, double Second);
    
    
    
    double InterestAmount(double P, double r, double t);
    
    }
    
    
    
    #endif
  8. Create a header file and save it as Main.h (make sure you include the .h extension)
  9. To make the Main.cpp file less crowded, in the Main.h file, define the following accessory functions in their own namespace:
     
    #if !defined MainH
    
    #define      MainH
    
    #include <iostream>
    
    
    
    using namespace std;
    
    namespace Accessories
    
    {
    
    // Accessory Functions
    
    
    
    // This function adds two values
    
    double Addition(double Value1, double Value2)
    
    {
    
        return Value1 + Value2;
    
    }
    
    
    
    // This function takes two arguments.
    
    // It subtracts the second from the first
    
    double Subtraction(double Value1, double Value2)
    
    {
    
        return Value1 - Value2;
    
    }
    
    
    
    // This function multiplies two numbers
    
    double Multiplication(double Value1, double Value2)
    
    {
    
        return Value1 * Value2;
    
    }
    
    
    
    // This function takes two arguments
    
    // If the second argument is 0, the function returns 0
    
    // Otherwise, the first argument is divided by the second
    
    double Division(double Numerator, double Denominator)
    
    {
    
        if( Denominator == 0 )
    
            return 0;
    
        // else is implied
    
        return Numerator / Denominator;
    
    }
    
    }   // namespace Accessories
    
    
    
    namespace LoanProcessing
    
    {
    
    
    
    double GetPrincipal()
    
    {
    
        double P;
    
    
    
        cout << "Enter the Principal: $"; cin >> P;
    
        return P;
    
    }
    
    
    
    double GetInterestRate()
    
    {
    
        double r;
    
    
    
        cout << "Enter the Interest Rate (%): "; cin >> r;
    
        return r;
    
    }
    
    
    
    double GetPeriod(int &TypeOfPeriod, double &Periods)
    
    {
    
        cout << "How do you want to enter the length of time?";
    
        cout << "\n1 - In Days";
    
        cout << "\n2 - In Months";
    
        cout << "\n3 - In Years";
    
        cout << "\nYour Choice: "; cin >> TypeOfPeriod;
    
    
    
        if( TypeOfPeriod == 1 )
    
        {
    
            cout << "Enter the number of days: "; cin >> Periods;
    
            return static_cast<double>(Periods / 360);
    
        }
    
        else if( TypeOfPeriod == 2 )
    
        {
    
            cout << "Enter the number of months: "; cin >> Periods;
    
            return static_cast<double>(Periods / 12);
    
        }
    
        else if( TypeOfPeriod == 3 )
    
        {
    
            cout << "Enter the number of years: "; cin >> Periods;
    
            return static_cast<double>(Periods);
    
        }
    
        else
    
        {
    
            TypeOfPeriod = 0;
    
            // The user made an invalid selection. So, we will give up
    
            cout << "\nBad Selection\n";
    
            return 0.00;
    
        }
    
    }
    
    
    
    }
    
    
    
    #endif  // MainH
  10. To prepare a test for the new changes, change the Main.cpp file as follows:
     
    
    #include <iostream>
    
    using namespace std;
    
    
    
    #include "Main.h"
    
    #include "Loan.h"
    
    
    
    
    
    int main()
    
    {
    
        // Declare a variable of type Add, defined in the Finance namespace
    
        Finance::Add Plus;
    
    
    
        double Principal, IntRate, Period, InterestAmount;
    
        int    TypeOfPeriod;
    
        double Periods;
    
        string PeriodName;
    
    
    
        cout << "This program allows you to calculate the amount of money a "
    
             << "customer will owe at the end of the lifetime of a loan\n";
    
    
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
    
        cout << "\nLoan Processing\n";
    
        Principal      = LoanProcessing::GetPrincipal();
    
        IntRate        = LoanProcessing::GetInterestRate();
    
        Period         = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);
    
        Plus           = Accessories::Addition;
    
        InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); 
    
        double Amount  = Plus(Principal, InterestAmount);
    
    
    
        if( TypeOfPeriod == 0 )
    
        {
    
            // Since the user made a bad selection, stop the program here
    
            cout << "Press any key to stop...";
    
            
    
            return 0;
    
        }
    
    
    
        if( TypeOfPeriod == 1 )
    
        {
    
            PeriodName = " Days";
    
        }
    
        else if( TypeOfPeriod == 2 )
    
        {
    
            PeriodName = " Months";
    
        }
    
        else if( TypeOfPeriod == 3 )
    
        {
    
            PeriodName = " Years";
    
        }
    
        cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
    
    
    
        cout << "\n==================================";
    
        cout << "\nEstimate on loan";
    
        cout << "\n----------------------------------";
    
        cout << "\nPrincipal: $" << Principal;
    
        cout << "\nInterest:   " << IntRate << "%";
    
        cout << "\nPeriod:     " << Periods << PeriodName;  
    
        cout << "\n--------------------------------";
    
        cout << "\nInterest paid on Loan: $" << InterestAmount; 
    
        cout << "\nTotal Amount Paid:     $" << Amount;
    
        cout << "\n==================================\n";
    
        
    
        return 0;
    
    }
    
    
  11. Test the application and return to your programming environment
  12. Save All

A Pointer to a Function as Argument

your programming environmentUsing pointer to functions, a function can be passed as argument to another function. The function must be passed as a pointer. The argument is declared in a complete format as if you were declaring a function. Here is an example of a function that is passed a function as argument.

double Circumference(double (*FDiam)(double R))

This Circumference() function takes one argument. The argument itself is a pointer to function. This argument itself takes a double-precision number as argument and it returns a double-precision value. The Circumference() function returns a double-precision number.

It is important to know that the pointer to function that is passed as argument is declared completely, in this case as

double (*FDiam)(double R)

Although the FDiam declaration is accompanied by an argument, in this case R, this argument allows the compiler to know that FDiam takes an argument. This argument actually will not be processed by the Circumference() function when the Circumference() function is defined because the R argument does not belong to the Circumference() function.

When calling the Circumference() function, you will use the FDiam argument as a variable in its own right, using its name, as in

Circumference(Diameter)

When defining the Circumference() function, you must process the pointer to function that it takes as argument. If this argument is an alias to a function that returns a value, you can call it and pass it the argument as we studied in the last section. If you want to involve the FDiam argument in any operation, you can declare a local variable to the Circumference() function. If the FDiam argument must be involved in an operation that involves a value external to the Circumference() function, you must pass that type of value as argument to the Circumference() function, unless you are using a global variable (we will study global variables when we review the issue of scopes). This means that, in most circumstances, the pointer to function passed as argument may be accompanied by at least one other argument. For example, if you want to use the FDiam as a diameter value to calculate the circumference (Circumference = Diameter * PI), you may have to declare it with an argument for the radius. It would be declared as follows:

double Circumference(double (*FDiam)(double R), double Rad);

The function can then be implemented as follows:

double Circumference(double (*FDiam)(double R), double Rad)

{

    double Circf;

    const double PI = 3.14159;

    Circf = (*FDiam)(Rad);



    return Circf * PI;

}

Remember that, when declaring a function, the compiler does not care about the name(s) of the argument(s). If the function takes any, what the compiler cares about are the return type of the function, its name, and the type(s) of its argument(s), if any. Therefore, the above function could as well be declared as follows:

double Circumference(double (*)(double R), double);

This indicates that the Circumference() function takes two arguments whose names are not known. The first argument is a pointer to a function that takes one double-precision number as argument and returns a double. The second argument of the Circumference() function is also a double-precision number. The Circumference() function returns a double-precision number. This is what the program at this time would look like:


#include <iostream>

using namespace std;







double Diameter(double);

double Circumference(double (*D)(double R), double r);



int main()

{

    double Radius;



    Radius = 25.52;



    cout << "Cylinder Summary";

    cout << "\nRadius:   " << Radius;

    cout << "\nCircumference = " << Circumference(Diameter, Radius) << endl;

    

    return 0;

}



double Diameter(double Rad)

{

    return Rad * 2;

}



double Circumference(double (*FDiam)(double R), double Rad)

{

    double Circf;

    const double PI = 3.14159;

    Circf = (*FDiam)(Rad);



    return Circf * PI;

}

This would produce:

Cylinder Summary

Radius:   25.52

Circumference = 160.347



Press any key to continue...

To simplify the declaration of a pointer to function, we saw that you can create a programmer-defined type using the typedef keyword. This can also help when passing a function as argument. Here is an example:

typedef double (*FDiam)(double R);

double Circumference(FDiam, double);

When creating such a programmer-defined type, remember that you must give a name to the alias, in this case FDiam. After this creation, FDiam is an alias to a pointer to function of a double-precision type and which takes one double-precision number as argument.

Remember, as we learned when studying functions that return a value, that the item on the right side of the return keyword can be a value or a complete expression. Therefore, you can simplify the implementation of the Circumference() function as follows:


double Circumference(double (*FDiam)(double R), double Rad)

{

    const double PI = 3.14159;

    return (*FDiam)(Rad) * PI;

}

 

Practical LearningPractical Learning: Passing a Function as Argument

  1. To declare a function that takes another function as argument, in the Loan.h file, declare the following function:
     
    #ifndef LoanH
    #define LoanH
    
    namespace Finance
    {
    typedef double (*Add)(double R, double T);
    typedef double (*Subtract)(double First, double Second);
    typedef double (*Multiply)(double First, double Second);
    typedef double (*Divide)(double First, double Second);
    
    double InterestAmount(double P, double r, double t);
    double Rate(double (*AP)(double A, double P),
                           double a, double p, double t);
    }
    
    #endif
  2. In the Loan.cpp, implement the function as follows:
     
    #include "Loan.h"
    
    #pragma package(smart_init)
    
    namespace Finance
    {
        // Interest = Principal * rate * time in years
        double InterestAmount(double P, double r, double t)
        {
            return P * (r / 100) * t;
        }
    
        double Rate(double (*AP)(double A, double P),
                           double a, double p, double t)
        {
            double AMinusP = (*AP)(a, p);
            double Pt      = p * t;
    
            return (AMinusP / Pt) * 100;
        }
    }
  3. To provide a function used to get the future value of a loan, in the Main.h file, define a GetAmount() function as follows:
     
    #if !defined MainH
    #define      MainH
    
    . . . No Change
    
    namespace LoanProcessing
    {
        double GetAmount()
        {
            double A;
    
            cout << "Enter the future value: $"; cin >> A;
    
            return A;
    }
    
    . . . No Change
    
    #endif  // MainH
  4. To call the new function, change the Main.cpp file as follows:
     
    #include <iostream>
    
    #include "Main.h"
    #include "Loan.h"
    
    using namespace std;
    using namespace Accessories;
    
    int main()
    {
        double Principal, Amount, IntRate, Period, InterestAmount;
        int    TypeOfPeriod;
        double Periods;
        string PeriodName;
    
        cout << "This program allows you to perform estimations on loans\n";
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
        cout << "\nLoan Processing\n";
        Amount    = LoanProcessing::GetAmount();
        Principal = LoanProcessing::GetPrincipal();
        Period    = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);
        IntRate   = Finance::Rate(Subtraction, Amount, Principal, Period);
    
        if( TypeOfPeriod == 0 )
        {
            // Since the user made a bad selection, stop the program here
            cout << "Press any key to stop...";
    
            return 0;
        }
    
        if( TypeOfPeriod == 1 )
        {
            PeriodName = " Days";
        }
        else if( TypeOfPeriod == 2 )
        {
            PeriodName = " Months";
        }
        else if( TypeOfPeriod == 3 )
        {
            PeriodName = " Years";
        }
    
        cout << "\n==================================";
        cout << "\nEstimate on loan";
        cout << "\n----------------------------------";
        cout << "\nFuture Value: $" << Amount;
        cout << "\nPrincipal:    $" << Principal;
        cout << "\nPeriod:        " << Periods << PeriodName;
        cout << "\n--------------------------------";
        cout << "\nInterest on Loan: " << IntRate << "%";
        cout << "\n==================================\n";
    
        return 0;
    }
  5. Test the application. Here is an example:
     
    This program allows you to perform estimations on loans
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Loan Processing
    Enter the future value: $4500
    Enter the Principal: $3000
    How do you want to enter the length of time?
    1 - In Days
    2 - In Months
    3 - In Years
    Your Choice: 3
    Enter the number of years: 3
    
    ==================================
    Estimate on loan
    ----------------------------------
    Future Value: $4500
    Principal:    $3000
    Period:        3 Years
    --------------------------------
    Interest on Loan: 16.6667%
    ==================================
    Press any key to continue...
  6. To provide more options to the user and make the program more complete, you can create a menu, allowing the clerk to select the type of calculation. A customer may want to know how much time would be a better length of time to pay a loan. The customer may want to find the differences among the time (period), the rate of interest, the monthly payment the customer can afford, the length of time (the number of days, months or years the customer wants to pay the loan.
    To allow the user to select the type of calculation to perform, in the Main.h file, define the following functions:
     
    #if !defined MainH
    
    #define      MainH
    
    #include <iostream>
    
    
    
    #include "Loan.h"
    
    
    
    using namespace std;
    
    namespace Accessories
    
    {
    
    // Accessory Functions
    
    
    
    // This function adds two values
    
    double Addition(double Value1, double Value2)
    
    {
    
        return Value1 + Value2;
    
    }
    
    
    
    // This function takes two arguments.
    
    // It subtracts the second from the first
    
    double Subtraction(double Value1, double Value2)
    
    {
    
        return Value1 - Value2;
    
    }
    
    
    
    // This function multiplies two numbers
    
    double Multiplication(double Value1, double Value2)
    
    {
    
        return Value1 * Value2;
    
    }
    
    
    
    // This function takes two arguments
    
    // If the second argument is 0, the function returns 0
    
    // Otherwise, the first argument is divided by the second
    
    double Division(double Numerator, double Denominator)
    
    {
    
        if( Denominator == 0 )
    
            return 0;
    
        // else is implied
    
        return Numerator / Denominator;
    
    }
    
    }   // namespace Accessories
    
    
    
    namespace LoanProcessing
    
    {
    
    
    
    double GetAmount()
    
    {
    
        double A;
    
    
    
        cout << "Enter the future value: $"; cin >> A;
    
        return A;
    
    }
    
    
    
    double GetPrincipal()
    
    {
    
        double P;
    
    
    
        cout << "Enter the Principal: $"; cin >> P;
    
        return P;
    
    }
    
    
    
    double GetInterestRate()
    
    {
    
        double r;
    
    
    
        cout << "Enter the Interest Rate (%): "; cin >> r;
    
        return r;
    
    }
    
    
    
    double GetPeriod(int &TypeOfPeriod, double &Periods)
    
    {
    
        cout << "How do you want to enter the length of time?";
    
        cout << "\n1 - In Days";
    
        cout << "\n2 - In Months";
    
        cout << "\n3 - In Years";
    
        cout << "\nYour Choice: "; cin >> TypeOfPeriod;
    
    
    
        if( TypeOfPeriod == 1 )
    
        {
    
            cout << "Enter the number of days: "; cin >> Periods;
    
            return static_cast<double>(Periods / 360);
    
        }
    
        else if( TypeOfPeriod == 2 )
    
        {
    
            cout << "Enter the number of months: "; cin >> Periods;
    
            return static_cast<double>(Periods / 12);
    
        }
    
        else if( TypeOfPeriod == 3 )
    
        {
    
            cout << "Enter the number of years: "; cin >> Periods;
    
            return static_cast<double>(Periods);
    
        }
    
        else
    
        {
    
            TypeOfPeriod = 0;
    
            // The user made an invalid selection. So, we will give up
    
            cout << "\nBad Selection\n";
    
            return 0.00;
    
        }
    
    }
    
    
    
    int SelectCalculationType()
    
    {
    
        int Answer;
    
    
    
        cout << "What kind of value do you want to estimate?";
    
        cout << "\n1 - Calculate (only) the interest paid on the loan";
    
        cout << "\n2 - Estimate the future value of the entire loan";
    
        cout << "\nYour choice: ";
    
        cin >> Answer;
    
    
    
        return Answer;
    
    }
    
    
    
    void ProcessInterestAmount()
    
    {
    
        double Principal, IntRate, Period, InterestAmount;
    
        int    TypeOfPeriod;
    
        double Periods;
    
        string PeriodName;
    
    
    
        cout << "\nWe will calculate the interest amount payed on a loan\n";
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
    
        cout << "\nLoan Processing\n";
    
        Principal      = LoanProcessing::GetPrincipal();
    
        IntRate        = LoanProcessing::GetInterestRate();
    
        Period         = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);
    
        InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);
    
    
    
        if( TypeOfPeriod == 0 )
    
        {
    
            // Since the user made a bad selection, stop the program here
    
            cout << "Press any key to stop...";
    
            
    
            return;
    
        }
    
    
    
        if( TypeOfPeriod == 1 )
    
        {
    
            PeriodName = " Days";
    
        }
    
        else if( TypeOfPeriod == 2 )
    
        {
    
            PeriodName = " Months";
    
        }
    
        else if( TypeOfPeriod == 3 )
    
        {
    
            PeriodName = " Years";
    
        }
    
        cout << "\n";
    
    
    
        cout << "\n==================================";
    
        cout << "\nEstimate on loan";
    
        cout << "\n----------------------------------";
    
        cout << "\nPrincipal: $" << Principal;
    
        cout << "\nInterest:   " << IntRate << "%";
    
        cout << "\nPeriod:     " << Periods << PeriodName;
    
        cout << "\n--------------------------------";
    
        cout << "\nInterest paid on Loan: $" << InterestAmount;
    
        cout << "\n==================================\n";
    
    }
    
    
    
    void ProcessRateOfInterest()
    
    {
    
        double Principal, Amount, IntRate, Period;
    
        int    TypeOfPeriod;
    
        double Periods;
    
        string PeriodName;
    
    
    
        cout << "\nWe will calculate the interest rate applied on a loan\n";
    
        cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
    
        cout << "\nLoan Processing\n";
    
        Amount    = LoanProcessing::GetAmount();
    
        Principal = LoanProcessing::GetPrincipal();
    
        Period    = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);
    
        IntRate   = Finance::Rate(Accessories::Subtraction, Amount, Principal, Period);
    
    
    
        if( TypeOfPeriod == 0 )
    
        {
    
            // Since the user made a bad selection, stop the program here
    
            cout << "Press any key to stop...";
    
            
    
            return;
    
        }
    
    
    
        if( TypeOfPeriod == 1 )
    
        {
    
            PeriodName = " Days";
    
        }
    
        else if( TypeOfPeriod == 2 )
    
        {
    
            PeriodName = " Months";
    
        }
    
        else if( TypeOfPeriod == 3 )
    
        {
    
            PeriodName = " Years";
    
        }
    
    
    
        cout << "\n==================================";
    
        cout << "\nEstimate on loan";
    
        cout << "\n----------------------------------";
    
        cout << "\nFuture Value: $" << Amount;
    
        cout << "\nPrincipal:    $" << Principal;
    
        cout << "\nPeriod:        " << Periods << PeriodName;
    
        cout << "\n--------------------------------";
    
        cout << "\nInterest on Loan: " << IntRate << "%";
    
        cout << "\n==================================\n";
    
    }
    
    
    
    }
    
    
    
    #endif  // MainH
  7. To test the new version of the program, change the Main.cpp file as follows:
     
    #include <iostream>
    
    #include "Main.h"
    #include "Loan.h"
    
    using namespace std;
    using namespace Accessories;
    using namespace LoanProcessing;
    
    int main()
    {
        int TypeOfCalculation;
    
        cout << "This program allows you to perform estimations on loans\n";
    
        TypeOfCalculation = SelectCalculationType();
    
        switch(TypeOfCalculation)
        {
        case 1:
            ProcessInterestAmount();
            break;
    
        case 2:
            ProcessRateOfInterest();
            break;
    
        default:
            cout << "\nInvalid Selection\n";
        }
    
        return 0;
    }
  8. Test the application and return to your programming environment
  9. To allow the clerk to process other types of calculations, in the Loan.h file, declare the following functions:
     
    #ifndef LoanH
    #define LoanH
    
    namespace Finance
    {
    typedef double (*Add)(double R, double T);
    typedef double (*Subtract)(double First, double Second);
    typedef double (*Multiply)(double First, double Second);
    typedef double (*Divide)(double First, double Second);
    
    double InterestAmount(double P, double r, double t);
    
    double Rate(double (*AP)(double A, double P),
                           double a, double p, double t);
    
    double TotalLoanAmount(double P, double r, double t);
    
    double PrincipalAmount(double (*RT)(double a, double b),
                                      double R, double T, double A);
    
    double Period(double (*AP)(double A, double P),
                             double (*PR)(double P, double R),
                             double a, double p, double r);
    
    double Period(double (*AP)(double A, double P),
                             double a, double p, double r);
    }
    
    #endif
  10. In the Loan.cpp file, implement the functions:
     
    #include "Loan.h"
    
    #pragma package(smart_init)
    
    namespace Finance
    {
        // Interest = Principal * rate * time in years
        double InterestAmount(double P, double r, double t)
        {
            return P * (r / 100) * t;
        }
    
        //                            Amount - Principal
        // Interest rate of a loan = --------------------
        //                            Principal * Period
        double Rate(double (*AP)(double A, double P),
                           double a, double p, double t)
        {
            double AMinusP = (*AP)(a, p);
            double Pt      = p * t;
    
            return (AMinusP / Pt) * 100;
        }
    
        // Amount = Principal(1 + Rate * Interest)
        double TotalLoanAmount(double P, double r, double t)
        {
            return P * (1 + ((r / 100) * t));
        }
    
        //                  Amount
        // Principal = ------------------
        //             1 + Rate * Period
        double PrincipalAmount(double (*RT)(double a, double b),
                                      double R, double T, double A)
        {
            double RateOnTime = (*RT)(R/100, T);
            return A / (1 + RateOnTime);
        }
    
    //                            Amount - Principal
    // Interest rate of a loan = --------------------
    //                            Principal * Rate
    // The following function provides a very simplistic way to calculate the
    // length of time of a loan. In fact, there is no checking on the
    // periodic value (whether the value is in days, quarters, months, or
    // years, and there is no algorithm to check the value of the time
        double Period(double (*AP)(double A, double P),
                             double (*PR)(double P, double R),
                             double a, double p, double r)
        {
            double AMinusP = (*AP)(a, p);
            double PTimesR = (*PR)(p, r / 100);
    
            return AMinusP / PTimesR;
        }
    }
  11. To expand the menu, change the Main.h file accordingly:
     
    #if !defined MainH
    #define      MainH
    
    #include <iostream>
    
    #include "Loan.h"
    
    using namespace std;
    
    namespace Accessories
    {
        // Accessory Functions
        // This function adds two values
        double Addition(double Value1, double Value2)
        {
            return Value1 + Value2;
        }
    
        // This function takes two arguments.
        // It subtracts the second from the first
        double Subtraction(double Value1, double Value2)
        {
            return Value1 - Value2;
        }
        // This function multiplies two numbers
        double Multiplication(double Value1, double Value2)
        {
            return Value1 * Value2;
        }
    
        // This function takes two arguments
        // If the second argument is 0, the function returns 0
        // Otherwise, the first argument is divided by the second
        double Division(double Numerator, double Denominator)
        {
            if( Denominator == 0 )
                return 0;
            // else is implied
            return Numerator / Denominator;
        }
    }   // namespace Accessories
    
    namespace LoanProcessing
    {
        double GetAmount()
        {
            double A;
    
            cout << "Enter the future value: $"; cin >> A;
    
            return A;
        }
    
        double GetPrincipal()
        {
            double P;
    
            cout << "Enter the Principal: $"; cin >> P;
    
            return P;
        }
    
    double GetInterestRate()
    {
        double r;
    
        cout << "Enter the Interest Rate (%): "; cin >> r;
    
        return r;
    }
    
    double GetPeriod(int &TypeOfPeriod, double &Periods)
    {
        cout << "How do you want to enter the length of time?";
        cout << "\n1 - In Days";
        cout << "\n2 - In Months";
        cout << "\n3 - In Years";
        cout << "\nYour Choice: "; cin >> TypeOfPeriod;
    
        if( TypeOfPeriod == 1 )
        {
            cout << "Enter the number of days: "; cin >> Periods;
    
            return static_cast<double>(Periods / 360);
        }
        else if( TypeOfPeriod == 2 )
        {
            cout << "Enter the number of months: "; cin >> Periods;
            return static_cast<double>(Periods / 12);
        }
        else if( TypeOfPeriod == 3 )
        {
            cout << "Enter the number of years: "; cin >> Periods;
            return static_cast<double>(Periods);
        }
        else
        {
            TypeOfPeriod = 0;
            // The user made an invalid selection. So, we will give up
            cout << "\nBad Selection\n";
    
            return 0.00;
        }
    }
    
    int SelectCalculationType()
    {
        int Answer;
    
        cout << "What kind of value do you want to estimate?";
        cout << "\n1 - Calculate (only) the interest paid on the loan";
        cout << "\n2 - Calculate the total amount owed on a loan";
        cout << "\n3 - Estimate the interest rate applied on a loan";
        cout << "\n4 - Find the amount given as loan";
        cout << "\n5 - Find the approximate length of time of a loan";
        cout << "\nYour choice: ";
        cin >> Answer;
    
        return Answer;
    }
    
    void ProcessInterestAmount(bool GetTotalAmount = false)
    {
        double Principal, Amount, IntRate, Period, InterestAmount;
        int    TypeOfPeriod;
        double Periods;
        string PeriodName;
    
        cout << "\n=====================================================";
        cout << "\nWe will calculate the interest amount payed on a loan\n";
        cout << "\n=====================================================";
        cout << "\nLoan Processing\n";
        Principal      = LoanProcessing::GetPrincipal();
        IntRate        = LoanProcessing::GetInterestRate();
        Period         = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);
    
        if( TypeOfPeriod == 0 )
        {
            // Since the user made a bad selection, get out of the function 
            cout << "\nThe program will stop";
            return;
        }
    
        InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);
        Amount         = Finance::TotalLoanAmount(Principal, IntRate, Period);
    
        if( TypeOfPeriod == 1 )
        {
            PeriodName = " Days";
        }
        else if( TypeOfPeriod == 2 )
        {
            PeriodName = " Months";
        }
        else if( TypeOfPeriod == 3 )
        {
            PeriodName = " Years";
        }
        cout << "\n";
        cout << "\n==================================";
        cout << "\nEstimate on loan";
        cout << "\n----------------------------------";
        cout << "\nPrincipal: $" << Principal;
        cout << "\nInterest:   " << IntRate << "%";
        cout << "\nPeriod:     " << Periods << PeriodName;
        cout << "\n--------------------------------";
        cout << "\nInterest paid on Loan: $" << InterestAmount;
    
        if( GetTotalAmount == true )
            cout << "\nTotal Amount Paid:     $" << Amount;
        cout << "\n==================================\n";
    }
    
    void ProcessRateOfInterest()
    {
        double Principal, Amount, IntRate, Period;
        int    TypeOfPeriod;
        double Periods;
        string PeriodName;
    
        cout << "\n=====================================================";
        cout << "\nWe will calculate the interest rate applied on a loan\n";
        cout << "\n=====================================================";
        cout << "\nLoan Processing\n";
        Amount    = LoanProcessing::GetAmount();
        Principal = LoanProcessing::GetPrincipal();
        Period    = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);
    
        if( TypeOfPeriod == 0 )
        {
            // Since the user made a bad selection, get out of the function
            cout << "\nThe program will stop";
            return;
        }
    
        IntRate   = Finance::Rate(Accessories::Subtraction, Amount,
                                  Principal, Period);
        if( TypeOfPeriod == 1 )
        {
            PeriodName = " Days";
        }
        else if( TypeOfPeriod == 2 )
        {
            PeriodName = " Months";
        }
        else if( TypeOfPeriod == 3 )
        {
            PeriodName = " Years";
        }
    
        cout << "\n==================================";
        cout << "\nEstimate on loan";
        cout << "\n----------------------------------";
        cout << "\nFuture Value: $" << Amount;
        cout << "\nPrincipal:    $" << Principal;
        cout << "\nPeriod:        " << Periods << PeriodName;
        cout << "\n--------------------------------";
        cout << "\nInterest on Loan: " << IntRate << "%";
        cout << "\n==================================\n";
    }
    
    void ProcessPrincipal()
    {
        double Principal, Amount, IntRate, Period;
        int    TypeOfPeriod;
        double Periods;
        string PeriodName;
    
        cout << "\n==================================================";
        cout << "\nWe will calculate the principal value of the loan";
        cout << "\n==================================================";
        cout << "\nLoan Processing\n";
        Amount    = LoanProcessing::GetAmount();
        IntRate   = LoanProcessing::GetInterestRate();
        Period    = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);
    
        if( TypeOfPeriod == 0 )
        {
            // Since the user made a bad selection, get out of the function
            cout << "\nThe program will stop";
            return;
        }
    
        Principal = Finance::PrincipalAmount(Accessories::Multiplication,
                                             IntRate, Period, Amount);
        if( TypeOfPeriod == 1 )
        {
            PeriodName = " Days";
        }
        else if( TypeOfPeriod == 2 )
        {
            PeriodName = " Months";
        }
        else if( TypeOfPeriod == 3 )
        {
            PeriodName = " Years";
        }
    
        cout << "\n==================================";
        cout << "\nEstimate on loan";
        cout << "\n----------------------------------";
        cout << "\nFuture Value: $" << Amount;
        cout << "\nInterest on Loan: " << IntRate << "%";
        cout << "\nPeriod:        " << Periods << PeriodName;
        cout << "\n--------------------------------";
        cout << "\nPrincipal:    $" << Principal;
        cout << "\n==================================\n";
    }
    
    void ProcessPeriod()
    {
        double Principal, Amount, IntRate, TimeSpan;
        int    TypeOfPeriod;
        double Periods;
        string PeriodName;
    
        cout << "\n=====================================================";
        cout << "\nWe will calculate the amount of time to pay a loan\n";
        cout << "\n=====================================================";
        cout << "\nLoan Processing\n";
        Amount    = LoanProcessing::GetAmount();
        Principal = LoanProcessing::GetPrincipal(); 
        IntRate   = LoanProcessing::GetInterestRate();
        TimeSpan  = Finance::Period(Accessories::Subtraction,
                                    Accessories::Multiplication,
                                    Amount, Principal, IntRate);
        cout << "\n==================================";
        cout << "\nEstimate on loan";
        cout << "\n----------------------------------";
        cout << "\nFuture Value: $" << Amount;
        cout << "\nPrincipal:    $" << Principal;
        cout << "\nInterest on Loan: " << IntRate << "%";
        cout << "\n--------------------------------";
        cout << "\nPeriod:        " << TimeSpan * 12 << " Months";
        cout << "\n==================================\n";
    }
    }
    
    #endif  // MainH
  12. To prepare for a test, in the Main.cpp, add the new options in the main() function:
     
    #include <iostream>
    
    #include "Main.h"
    #include "Loan.h"
    
    using namespace std;
    using namespace Accessories;
    using namespace LoanProcessing;
    
    int main()
    {
        int TypeOfCalculation;
    
        cout << "This program allows you to perform estimations on loans\n";
        TypeOfCalculation = SelectCalculationType();
    
        switch(TypeOfCalculation)
        {
        case 1:
            ProcessInterestAmount();
            break;
    
        case 2:
            ProcessInterestAmount(true);
            break;
    
        case 3:
            ProcessRateOfInterest();
            break;
    
        case 4:
            ProcessPrincipal();
            break;
    
        case 5:
            ProcessPeriod();
            break;
    
        default:
            cout << "\nInvalid Selection\n";
        }
    
        return 0;
    }
  13. Test the application. Here is an example:
     
    This program allows you to perform estimations on loans
    What kind of value do you want to estimate?
    1 - Calculate (only) the interest paid on the loan
    2 - Calculate the total amount owed on a loan
    3 - Estimate the interest rate applied on a loan
    4 - Find the amount given as loan
    5 - Find the approximate length of time of a loan
    Your choice: 5
    
    =====================================================
    We will calculate the amount of time to pay a loan
    =====================================================
    Loan Processing
    Enter the future value: $824
    Enter the Principal: $800
    Enter the Interest Rate (%): 9
    
    ==================================
    Estimate on loan
    ----------------------------------
    Future Value: $824
    Principal:    $800
    Interest on Loan: 9%
    --------------------------------
    Period:        4 Months
    ==================================
    
    Press any key to continue...
  14. Return to your programming environment and save everything

An Array of (Pointers to) Functions

To further refine the call to a group of functions that perform the same kind of task, you can declare an array of pointers to a type of function. Before creating an array of pointers to function, you must first know or have the functions you would be referring to. These functions must have a similar signature. This means that they must return the same type of value, they must have the same number of arguments and they must  have the  same type(s) of argument(s). Here are examples of such functions:

double Diameter(double Radius)
{
    return Radius * 2;
}

double Circumference(double Radius)
{
    return Diameter(Radius) * PI;
}

double Area(double Radius)
{
    return Radius * Radius * PI;
}

To declare an array of pointers to function, you can first define an alias to the variable. This is an example:

typedef double (*Measure)(double R);

After this definition, as we learned already, Measure is an alias to a function that takes a double type of variable and returns a double value. Using this name, you can declare an array of functions. The members of the array are names of the functions that would compose the array. Here is an example:

Measure Calc[] = { Diameter, Circumference, Area };

You can initialize each member using its index and calling the corresponding function. This can be done as follows:

#include <iostream>
using namespace std;

const double PI = 3.14159;

double Diameter(double Radius)
{
    return Radius * 2;
}

double Circumference(double Radius)
{
    return Diameter(Radius) * PI;
}

double Area(double Radius)
{
    return Radius * Radius * PI;
}

int main()
{
    typedef double (*Measure)(double R);

    double R = 12.55;
    Measure Calc[] = { Diameter, Circumference, Area };
    double D = Calc[0](R);
    double C = Calc[1](R);
    double A = Calc[2](R);

    cout << "Circle Characteristics";
    cout << "\nDiameter:      " << D;
    cout << "\nCircumference: " << C;
    cout << "\nArea:          " << A << endl;
    return 0;
}

This would produce:

Circle Characteristics
Diameter:      25.1
Circumference: 78.8539
Area:          494.808

Press any key to continue...

Practical Learning Practical Learning: Using an Array of Functions

  1. Create a new project using the Console Wizard
  2. To save the project, create a new folder called Multiple Choice1
  3. Save the unit as Exercise and save the project as MCQ1
  4. To experiment with an array of functions, change the Exercise.cpp file as follows:
     
    #include <iostream>
    using namespace std;
    
    typedef char (*Question)();
    enum TMCQuestion { One, Two, Three, Four, Five };
    
    char Sequence()
    {
        char Answer;
    
        cout << "Which sequence of numbers does not appear to follow "
             << "a recognizable order?";
        cout << "\n(a)   3   9  27  33";
        cout << "\n(b)   3   6   9  12";
        cout << "\n(c)   2   4   6   8";
        cout << "\n(d) 102 204 408 816";
        cout << "\nAnswer: "; cin >> Answer;
        return Answer;
    }
    
    char Expression()
    {
        char Response;
    
        cout << "Select the best expression to complete the empty space";
        cout << "\nWhen ... drugs to a business address, traffickers often "
             << "omit a recipient name";
        cout << "\n(a) to send";
        cout << "\n(b) senders";
        cout << "\n(c) sending";
        cout << "\n(d) dealing";
        cout << "\nAnswer: "; cin >> Response;
        return Response;
    }
    
    char Sentence()
    {
        char Answer;
    
        cout << "Even ... there are 76,000 lawyers in that city, it is still "
             << "a small community";
        cout << "\n(a) although";
        cout << "\n(b) though";
        cout << "\n(c) for";
        cout << "\n(d) since";
        cout << "\nAnswer: "; cin >> Answer;
        return Answer;
    }
    
    char WrongWord()
    {
        char Wrong;
    
        cout << "Select the wrong word that would complete the sentence";
        cout << "\nFor this type of business, revenue gains are ...";
        cout << "\n(a) limited";
        cout << "\n(b) scarce";
        cout << "\n(c) limitless";
        cout << "\n(d) claiming";
        cout << "\nAnswer: "; cin >> Wrong;
        return Wrong;
    }
    
    char Right()
    {
        char Sentence;
    
        cout << "Select the right sentence";
        cout << "\n(a) The company is expecting to reducing inventory,"
             << "\n    control cost, and efficiency improvement.";
        cout << "\n(b) The company expects to reduce inventory,"
             << "\n    control cost, and improve efficiency.";
        cout << "\n(c) The company expects to reduce inventory,"
             << "\n    control cost, and improving efficiency.";
        cout << "\n(d) The company is expecting to reducing inventory,"
             << "\n    controlling cost, and efficiency improvement.";
        cout << "\nAnswer: "; cin >> Sentence;
        return Sentence;
    }
    
    void ValidateAnswer(const int QstNbr, const char Ans);
    
    int main()
    {
        const int NumberOfQuestions = 5;
        char ValidAnswer;
        char Answer[NumberOfQuestions];
    
        Question MCQ[] = { Sequence, Expression, Sentence, WrongWord, Right};
    
        for(int i = 0; i < NumberOfQuestions; i++)
        {
            cout << "Question " << i + 1 << endl;
            Answer[i] = MCQ[i]();
            ValidateAnswer(i+1, Answer[i]); 
            cout << "\n\nPress any key to continue...";
    
            clrscr();
        }
    
        return 0;
    }
    
    void ValidateAnswer(const int QstNbr, const char Ans)
    {
        switch(QstNbr)
        {
        case 1:
            if(Ans == 'a' || Ans == 'A')
                cout << "Right Answer";
            else
            {
                cout << "Wrong Answer - The right answer was 'a'";
    
                cout << "\n(a) Starting at 3, 3*3=9 and 3*9=27";
                cout << "\n    There is no obvious way to determine 33";
            }
            break;
    
        case 2:
            if(Ans == 'c' || Ans == 'C')
                cout << "Right answer";
            else
                cout << "Wrong Answer - The right answer was 'c'";
            break;
        case 3:
            if(Ans == 'b' || Ans == 'B')
                cout << "Right answer";
            else
                cout << "Wrong Answer - The right answer was 'b'";
            break;  
    
        case 4:
            if(Ans == 'd' || Ans == 'D')
                cout << "Right answer";
            else
                cout << "Wrong Answer - The right answer was 'd'";
            break;  
    
        case 5:
            if(Ans == 'b' || Ans == 'B')
                cout << "Right answer";
            else
                cout << "Wrong Answer - The right answer was 'b'";
            break;
    
        default:
            cout << "Invalid Answer";
        }
    }
  5. Test the application
  6. Return to your programming environment and save all
 

Previous Copyright © 1998-2011 FunctionX Next