Introduction to Parameters and Arguments

A Function with a Parameter

Introduction

To perform its action(s), a function may need some values. If you are creating a function that will need values, you must indicate it. To do this, when creating a function, in its parentheses, enter a data type and a name. Here is an example:

void ShowBedrooms(int value)
{
}

The combination of data type and name that you provide to a function is called a parameter. In the body of the function, you can use the parameter or ignore it. If you decide to use the parameter, you can involve it in any operation that is appropriate for its type. For example, if it is a number, you can involve it in any algebraic operation. If it is a string or any other type, use it anyway you want. Here is an example:

#include <iostream>
using namespace std;

void ShowBedrooms(int value)
{
    cout << "Bedrooms: " << value << '\n';
}

Remember that, in the body of the function, you can ignore the parameter. This means that, in the body of the function, you can decide not to use the parameter.

Practical LearningPractical Learning: Introducing Parameters

Calling a Function that Uses a Parameter

When calling a function that uses a parameter, you must provide a value for the parameter. When doing that, where necessary, you will type the name of the function followed by parentheses. In those parentheses, type a value for the parameter. The value you provide in the parentheses of the function is called an argument. The action of providing a value in the parentheses of the function is referred to as passing an argument to the function.

There are various ways you can pass an argument to a function. If you have the value you want to use, provide it in the parentheses of the function. The value must be of the type of the parameter of the function or the value must be compatible. Here are examples:

#include <iostream>
using namespace std;

void VisitBathrooms(float nbr)
{
    cout << "Bathrooms:      " << nbr << '\n';
}

void Identity(char type)
{
    auto value = "Unknown";

    if(type == 'C')
        value = "Condominium";
    else if (type == 'T')
        value = "Townhouse";
    else if (type == 'S')
        value = "Single Family";

    cout << "Property Type:  " << value << '\n';
}

void ShowBedrooms(int value)
{
    cout << "Bedrooms:       " << value << '\n';
}

void DisplayMarketValue(long value)
{
    cout << "Market Value:   " << value << '\n';
}

int main()
{
    cout << "=//= Altair Realtors =//=\n";
    cout << "-------------------------------\n";
    cout << "Property Description\n";
    Identity('S');
    ShowBedrooms(5);
    VisitBathrooms(3.5);
    DisplayMarketValue(752880);
    cout << "==============================\n";
}

This would produce:

=//= Altair Realtors =//=
-------------------------------
Property Description
Property Type:  Single Family
Bedrooms:       5
Bathrooms:      3.5
Market Value:   752880
==============================

Press any key to close this window . . .

In the above examples, we passed the values directly to the function calls. In some cases, the values will come from some variable. In that case, you can pass the name of the variable to the function. The name of the variable doesn't have to be the same as the name of the parameter. Here are examples:

#include <iostream>
using namespace std;

void VisitBathrooms(float nbr)
{
    cout << "Bathrooms:      " << nbr << '\n';
}

void Identity(char type)
{
    auto value = "Unknown";

    if(type == 'C')
        value = "Condominium";
    else if (type == 'T')
        value = "Townhouse";
    else if (type == 'S')
        value = "Single Family";

    cout << "Property Type:  " << value << '\n';
}

void ShowBedrooms(int value)
{
    cout << "Bedrooms:       " << value << '\n';
}

void DisplayMarketValue(long value)
{
    cout << "Market Value:   " << value << '\n';
}

int main()
{
    char propertyType = 'S';
    int    beds = 5;
    float  baths = 3.5;
    double price = 752880;

    cout << "=//= Altair Realtors =//=\n";
    cout << "-------------------------------\n";
    cout << "Property Description\n";
    Identity(propertyType);
    ShowBedrooms(beds);
    VisitBathrooms(baths);
    DisplayMarketValue(price);
    cout << "==============================\n";
}

Practical LearningPractical Learning: Introducing Parameters

  1. Change the document as follows:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        
    }
    double first3000, next2000, next5000, over10000;
    
    double EvaluateTaxLiability(double grossSalary)
    {
        /* https://www.dor.ms.gov/individual/tax-rates
         * Mississippi has a graduated tax rate.
         * There is no tax schedule for Mississippi income taxes.
         * The graduated income tax rate is:
         * 0% on the first $3,000 of taxable income.
         * 3% on the next  $2,000 of taxable income.
         * 4% on the next  $5,000 of taxable income.
         * 5% on all taxable income over $10,000.   */
    
        if((grossSalary > 0) and (grossSalary is <= 3000))
        {
            first3000 = 0.00;
            next2000  = 0.00;
            next5000  = 0.00;
            over10000 = 0.00;
        }
        else if((grossSalary > 3000) and (grossSalary is <= 5000))
        {
            first3000 = 0.00;
            next2000 = (grossSalary - 3000) * 3 / 100;
            next5000 = 0.00;
            over10000 = 0.00;
        }
        else if((grossSalary > 5000) and (grossSalary is <= 10000))
        {
            first3000 = 0.00;
            next2000 = 2000 * 3 / 100;
            next5000 = (grossSalary - 5000) * 4 / 100;
            over10000 = 0.00;
        }
        else // if(grossSalary > 10000)
        {
            first3000 = 0.00;
            next2000 = 2000 * 3 / 100;
            next5000 = 5000 * 4 / 100;
            over10000 = (grossSalary - 10000) * 5 / 100;
        }
    
        return first3000 + next2000 + next5000 + over10000;
    }
    
    double CalculateSalary(double grossSalary)
    {
        return grossSalary - EvaluateTaxLiability(grossSalary);
    }
    
    cout << "============================================");
    cout << " - Amazing DeltaX - State Income Tax -");
    cout << "--------------------------------------------");
    cout << "          -=- Mississippi -=-");
    cout << "============================================");
    
    cout << "Enter the information to prepare the taxes");
    cout << "Gross Salary:  ");
    double grossSalary = double.Parse(ReadLine());
    
    double taxAmount = EvaluateTaxLiability(grossSalary);
    
    cout << "============================================");
    cout << " - Amazing DeltaX - State Income Tax -");
    cout << "--------------------------------------------");
    cout << "          -=- Mississippi -=-");
    cout << "============================================");
    cout << $"Gross Salary:  {grossSalary:f}");
    cout << "--------------------------------------------");
    cout << $"First $3000:   {first3000:f}");
    cout << $"Next  $2000:   {next2000:f}");
    cout << $"Next  $5000:   {next5000:f}");
    cout << $"Over  $10,000: {over10000:f}");
    cout << "--------------------------------------------");
    cout << $"Tax Amount:    {taxAmount:f}");
    cout << $"Net Pay:       {CalculateSalary(grossSalary):f}");
    cout << "============================================");
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. When requested, for the Gross Salary, type 2249.65 and press Enter:
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Enter the information to prepare the taxes
    Gross Salary:  2249.65
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Gross Salary:  2249.65
    --------------------------------------------
    First $3000:   0.00
    Next  $2000:   0.00
    Next  $5000:   0.00
    Over  $10,000: 0.00
    --------------------------------------------
    Tax Amount:    0.00
    Net Pay:       2249.65
    ============================================
    
    Press any key to close this window . . .
  4. Press Enter to close the window and return to your programming environment
  5. To execute, press Ctrl + F5
  6. For the Gross Salary, type 4264.85 and press Enter
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Enter the information to prepare the taxes
    Gross Salary:  4264.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Gross Salary:  4264.85
    --------------------------------------------
    First $3000:   0.00
    Next  $2000:   37.95
    Next  $5000:   0.00
    Over  $10,000: 0.00
    --------------------------------------------
    Tax Amount:    37.95
    Net Pay:       4226.90
    ============================================
    
    Press any key to close this window . . .
  7. Press G to close the window and return to your programming environment
  8. To execute again12, on the main menu, click Debug -> Start Without Debugging
  9. For the Gross Salary, type 6288.95 and press Enter:
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Enter the information to prepare the taxes
    Gross Salary:  6288.95
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Gross Salary:  6288.95
    --------------------------------------------
    First $3000:   0.00
    Next  $2000:   60.00
    Next  $5000:   51.56
    Over  $10,000: 0.00
    --------------------------------------------
    Tax Amount:    111.56
    Net Pay:       6177.39
    ============================================
    
    Press any key to close this window . . .
  10. Press B to close the window and return to your programming environment
  11. To execute the project again, press Ctrl + F5
  12. For the Gross Salary, type 12464.85 and press Enter
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Enter the information to prepare the taxes
    Gross Salary:  12464.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Gross Salary:  12464.85
    --------------------------------------------
    First $3000:   0.00
    Next  $2000:   60.00
    Next  $5000:   200.00
    Over  $10,000: 123.24
    --------------------------------------------
    Tax Amount:    383.24
    Net Pay:       12081.61
    ============================================
    
    Press any key to close this window . . .
  13. Press H to close the window and return to your programming environment
  14. To reduce the code of the functions, change them as follows:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        double CalculateSalary(double grossSalary) => grossSalary - EvaluateTaxLiability(grossSalary);
    
    cout << "============================================");
    cout << " - Amazing DeltaX - State Income Tax -");
    cout << "--------------------------------------------");
    cout << "          -=- Mississippi -=-");
    cout << "============================================");
    
    cout << "Enter the information to prepare the taxes");
    cout << "Gross Salary:  ");
    double grossSalary = double.Parse(ReadLine());
    
    cout << "============================================");
    cout << " - Amazing DeltaX - State Income Tax -");
    cout << "--------------------------------------------");
    cout << "          -=- Mississippi -=-");
    cout << "============================================");
    cout << $"Gross Salary:  {grossSalary:f}");
    cout << "--------------------------------------------");
    cout << $"Tax Amount:    {EvaluateTaxLiability(grossSalary):f}");
    cout << $"Net Pay:       {CalculateSalary(grossSalary):f}");
    cout << "============================================");
    }
    
    double EvaluateTaxLiability(double grossSalary)
    {
        /* https://www.dor.ms.gov/individual/tax-rates
         * Mississippi has a graduated tax rate.
         * There is no tax schedule for Mississippi income taxes.
         * The graduated income tax rate is:
         * 0% on the first $3,000 of taxable income.?
         * 3% on the next  $2,000 of taxable income.?
         * 4% on the next  $5,000 of taxable income.
         * 5% on all taxable income over $10,000.   */
    
        if((grossSalary > 0) and (grossSalary is <= 3000))
            return 0.00;
        else if((grossSalary > 3000) and (grossSalary is <= 5000))
            return (grossSalary - 3000) * 3 / 100;
        else if((grossSalary > 5000) and (grossSalary is <= 10000))
            return (2000 * 3 / 100) + ((grossSalary - 5000) * 4 / 100);
        else // if(grossSalary > 10000)
            
        return (2000 * 3 / 100) + (5000 * 4 / 100) + ((grossSalary - 10000) * 5 / 100);
    }
  15. To execute, press Ctrl + F5
  16. For the Gross Salary, type 7495.85 and press Enter:
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Enter the information to prepare the taxes
    Gross Salary:  7495.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
              -=- Mississippi -=-
    ============================================
    Gross Salary:  7495.85
    --------------------------------------------
    Tax Amount:    159.83
    Net Pay:       7336.02
    ============================================
    Press any key to close this window . . .
  17. Press N to close the window and return to your programming environment
  18. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
  19. Create a new C++ Console App named TaxPreparation07
  20. Change the document as follows:
    #include <iostream>
    using namespace std;
    
    void Announce()
    {
    }
    
    string GetFilingStatus()
    {
        return;
    }
    
    double GetGrossSalary()
    {
        return 0.00;
    }
    
    int main()
    {
        double taxAmount = 0.00;
        double net_pay   = 0.00;
    }

Declaring a Function

You already know that, in C++, you can declare a function before defining it. This is also also possible for functions that use parameters. When declaring the function, make sure you provide its parameter starting with its data type. Here is an example:

#include <iostream>
using namespace std;

void ShowRecord(string name);

int main()
{
    string staff = "Raymond Kouma";

    cout << "Employee Record\n";
    cout << "--------------------------\n";

    ShowRecord(staff);

    cout << "==========================\n";
}

void ShowRecord(string person)
{
    cout << "Full Name: " << person << "\n";
}

When declaring a function that uses a parameter, you can omit the name of the parameter. You can provide just the data type of the parameter. Later, when defining the function, you must specify a name for the parameter. Here is an example:

#include <iostream>
using namespace std;

void ShowRecord(string);

int main()
{
    . . .
}

void ShowRecord(string person)
{
    cout << "Full Name: " << person << "\n";
}

Introduction to Recursion

Recursion if the ability for a function to call itself. A possible problem is that the function could keep calling itself and never stops. Therefore, the function must define how it would stop calling itself and get out of the body of the function.

A type of formula to create a recursive function is:

return-value function-name(parameter(s), if any)
{
    Optional Action . . .
    function-name();
    Optionan Action . . .
}

A recursive function starts with a return value. If it would not return a value, you can define it with void. After its name, the function can use 0, one, or more parameters. Most of the time, a recursive function uses at least one parameter that it would modify. In the body of the function, you can take the necessary actions. There are no particular steps to follow when implementing a recursive function but there are two main rules to observe:

For an example of counting decrementing even numbers, you could start by creating a function that uses a parameter of type integer. To exercise some control on the lowest possible values, we will consider only positive numbers. In the body of the function, we will display the current value of the argument, subtract 2, and recall the function itself. Here is our function:

#include <iostream>
using namespace std;

int number = 0;

void EvenNumbers(int a)
{
    if (a >= 1)
    {
        cout << "Even Number: " << a << endl;

        number += a;

        a -= 2;
        EvenNumbers(a);
    }
}

int main()
{
    // Calling a recursive function
    EvenNumbers(34);

    cout << "--------------------------------------------";
    cout << endl << "The total even numbers from 0 to 34 is: " << number;
}

Notice that the function calls itself in its body. This would produce:

Even Number: 34
Even Number: 32
Even Number: 30
Even Number: 28
Even Number: 26
Even Number: 24
Even Number: 22
Even Number: 20
Even Number: 18
Even Number: 16
Even Number: 14
Even Number: 12
Even Number: 10
Even Number: 8
Even Number: 6
Even Number: 4
Even Number: 2
--------------------------------------------
The total even numbers from 0 to 34 is: 306

Press any key to close this window . . .

Boolean Values and Functions

A Boolean Parameter

As is done with the parameters of the other types, you can create a function that uses a parameter of bool type. Here is an example:

void CalculatePayroll(bool fullTime)
{

}

In the body of the function, the parameter is treated as holding a true or false value. When calling the function, pass such a value or a variable that holds that value. Here is an example:

void CalculatePayroll(bool fullTime)
{

}

void ValidateEmploymentStatus()
{
    CalculatePayroll(false);
}

Returning a Boolean Value

You can create a function that produces a Boolean value. To do that, when creating the function, on the left side of the name of the function, type bool. In the body of the function, perform the desired operation(s). Before the closing curly bracket, type return followed by a Boolean value or expression. Here is an example:

bool Validate()
{
    bool a = true;
    
    return a;
}

Topics on Functions with Arguments

Deferred Definitions of Functions

You already know that you can declare a function before defining it. You also know that one way you can do that is to declare the function in the same file where it is defined. When it comes to a function that uses a parameter, the function declaration and the function definition must have the same type of parameter. Here are examples:

#include <iostream>
using namespace std;

void VisitBathrooms(float nbr);
void Identity(char type);
void ShowBedrooms(int value);
void DisplayMarketValue(long value);

int main()
{
    char propertyType = 'T';
    int    beds = 3;
    float  baths = 2.5;
    double price = 325665;

    cout << "=//= Altair Realtors =//=\n";
    cout << "-------------------------------\n";
    cout << "Property Description\n";
    Identity(propertyType);
    ShowBedrooms(beds);
    VisitBathrooms(baths);
    DisplayMarketValue(price);
    cout << "==============================\n";
}

void VisitBathrooms(float nbr)
{
    cout << "Bathrooms:      " << nbr << '\n';
}

void Identity(char type)
{
    auto value = "Unknown";

    if (type == 'C')
        value = "Condominium";
    else if (type == 'T')
        value = "Townhouse";
    else if (type == 'S')
        value = "Single Family";

    cout << "Property Type:  " << value << '\n';
}

void ShowBedrooms(int value)
{
    cout << "Bedrooms:       " << value << '\n';
}

void DisplayMarketValue(long value)
{
    cout << "Market Value:   " << value << '\n';
}

This would produce:

=//= Altair Realtors =//=
-------------------------------
Property Description
Property Type:  Townhouse
Bedrooms:       3
Bathrooms:      2.5
Market Value:   325665
==============================

Press any key to close this window . . .

When declaring a function for deferred definition, you don't have to provide a name for the parameter of the function that is being declared, but you must provide a name for the parameter when defining the function. Here are examples:

#include <iostream>
using namespace std;

void VisitBathrooms(float);
void Identity(char);
void ShowBedrooms(int);
void DisplayMarketValue(long);

int main()
{
    . . .
}

void VisitBathrooms(float nbr)
{
    cout << "Bathrooms:      " << nbr << '\n';
}

void Identity(char type)
{
    . . .
}

void ShowBedrooms(int value)
{
    cout << "Bedrooms:       " << value << '\n';
}

void DisplayMarketValue(long value)
{
    cout << "Market Value:   " << value << '\n';
}

ApplicationPractical Learning: Accessing a Parameter by Name

  1. To change the functions in one-line code, change them as tollows:
    using static System.Console;
    
    void Announce()
    {
        . . .
    }
    
    string GetFilingStatus()
    {
        . . .
    }
    
    double GetGrossSalary()
    {
        . . .
    }
    
    double CalculateTaxAmount(string status, double salary)
    {
        . . .
    }
    
    double CalculateNetPay(double salary, double tax)
    {
        return salary - tax;
    }
    
    Announce();
    
    cout << "Enter the information for tax preparation");
    string filingStatus = GetFilingStatus();
    double grossSalary  = GetGrossSalary();
    
    double taxAmount = CalculateTaxAmount(salary: grossSalary, status: filingStatus);
    double net_pay   = CalculateNetPay(tax: taxAmount, salary: grossSalary);
    
    Announce();
    
    cout << $"Gross Salary:  {grossSalary:f}");
    cout << $"Filing Status: {filingStatus}");
    cout << "---------------------------------------------------------");
    cout << $"Tax Amount:    {taxAmount:f}");
    cout << $"Net Pay:       {net_pay:f}");
    cout << "=========================================================");
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. For the Filing Status, type S and press Enter
  4. For the Gross Salary, type 1688.85 and press Enter:
    =========================================================
     - Amazing DeltaX - State Income Tax -
    ---------------------------------------------------------
              -=- Georgia -=-
    =========================================================
    Enter the information for tax preparation
    Filing Status
    i - Single
    s - Married Filing Separate
    j - Married Filing Joint or Head of Household
    Enter Filing Status: S
    Gross Salary:        1688.85
    =========================================================
     - Amazing DeltaX - State Income Tax -
    ---------------------------------------------------------
              -=- Georgia -=-
    =========================================================
    Gross Salary:  1688.85
    Filing Status: Married Filing Separate
    ---------------------------------------------------------
    Tax Amount:    75.67
    Net Pay:       1613.18
    =========================================================
    Press any key to close this window . . .
  5. Press N to close the window and return to your programming environment

Inline Functions

When you call a function B() from function A(), function A() sends a request and must get to Function B(). This is sometimes cumbersome for long functions. Whenever your program includes a small function, C++ allows you to include such a function where it is being called. When function B() calls function A(), instead of sending a request to function A(), the compiler would include a copy of function A() into function B() where it is being called. Such a function (function A()) is referred to as an inline function.

To let you create an inline function, the C++ language provides a keyword named inline. To use it precede the function with this keyword. As one technique, you can write the keyword before the return type of the function. Here is an example:

#include <iostream>
using namespace std;

inline void Area(float side)
{
    cout << "\nThe area of the square is " << side * side;
}

int main()
{
    float s;

    cout << "Enter the side of the square: ";
    cin >> s;

    cout << "---------------------------------------";
    Area(s);
    cout << endl << "=======================================";
}

Here is an example of running the program:

Enter the side of the square: 247.793
---------------------------------------
The area of the square is 61401.4
=======================================
Press any key to close this window . . .

You can also write the inline keyword after the return type of the function. Here are examples:

#include <iostream>
using namespace std;

void inline RequestSalary(double& h);
inline double Daily(double h);
double inline Weekly(double h);
inline double BiWeekly(double h);
double inline Monthly(double h);
double inline Yearly(double h);

int main()
{
    double HourlySalary;

    cout << "This program allows you to evaluate your salary "
         << "for different periods\n";

    RequestSalary(HourlySalary);

    cout << "------------------------------------------------------------------------";
    cout << "\nBased on the hourly rate you supplied, here are your "
         << "periodic earnings";
    cout << "\n\tHourly:    $" << HourlySalary;
    cout << "\n\tDaily:     $" << Daily(HourlySalary);
    cout << "\n\tWeekly:    $" << Weekly(HourlySalary);
    cout << "\n\tBi-Weekly: $" << BiWeekly(HourlySalary);
    cout << "\n\tMonthly:   $" << Monthly(HourlySalary);
    cout << "\n\tYearly:    $" << Yearly(HourlySalary);
    cout << endl << "========================================================================";
}

void inline RequestSalary(double& x)
{
    cout << "Enter your hourly salary: $";
    cin >> x;
}

inline double Daily(double x)
{
    return x * 8;
}

double inline Weekly(double x)
{
    return Daily(x) * 5;
}

inline double BiWeekly(double x)
{
    return Weekly(x) * 2;
}

double inline Monthly(double x)
{
    return Weekly(x) * 4;
}

double inline Yearly(double h)
{
    return Monthly(h) * 12;
}

Here is an example of running the program:

This program allows you to evaluate your salary for different periods
Enter your hourly salary: $25.87
------------------------------------------------------------------------
Based on the hourly rate you supplied, here are your periodic earnings
        Hourly:    $25.87
        Daily:     $206.96
        Weekly:    $1034.8
        Bi-Weekly: $2069.6
        Monthly:   $4139.2
        Yearly:    $49670.4
========================================================================
Press any key to close this window . . .

A Void Parameter

In previous lessons, we saw that when a function doesn't use a paarameter, you leave its parentheses empty. As an option, you can write void in the parentheses of that function. When calling the function, leave its parentheses empty. Here are examples:

#include <iostream>
using namespace std;

int GetMiles(void)
{
    int miles = 0;

    cout << "Miles Driven:   ";
    cin >> miles;

    return miles;
}

double GetWorkRate(void)
{
    double pieceworkRate = 0.00;
    
    cout << "Piecework Rate: ";
    cin >> pieceworkRate;

    return pieceworkRate;
}

int main()
{
    int    a = GetMiles();
    double b = GetWorkRate();

    cout << "=========================";
    cout << "\n - Piece Work Delivery -";
    cout << "\n=========================";
    cout << "\nMiles Driven:   " << a;
    cout << "\nPiecework Rate: " << b;
    cout << "\n=========================";
}

A Parameter With an Optional Value

Consider the following code:

double originalPrice;

double CalculatePriceAfterDiscount(double discountRate)
{
    return originalPrice - (originalPrice * discountRate / 100);
}

We have learned that if a function uses a parameter, when you call that function, you must provide a value for the argument. Here is an example:

#include <iostream>
using namespace std;

double originalPrice;

double CalculatePriceAfterDiscount(double discountRate)
{
    return originalPrice - (originalPrice * discountRate / 100);
}

int main()
{
    double discountRate = 20.00; // 20%
    originalPrice = 198.75;

    double priceAfterDiscount = CalculatePriceAfterDiscount(discountRate);

    cout << "Fun Department Store\n";
    cout << "=========================\n";
    cout << "Orignial Price:  " << originalPrice << endl;
    cout << "Discount Rate:   " << discountRate << "%\n";
    cout << "-------------------------\n";
    cout << "Marked Price:    " << priceAfterDiscount << endl;
    cout << "=========================" << endl;
}

This would produce:

Fun Department Store
=========================
Orignial Price:  198.75
Discount Rate:   20%
-------------------------
Marked Price:    159
=========================

Press any key to close this window . . .

If you have a function whose argument is usually given the same value, you can give a default value to that parameter. To specify that a parameter has a default value, in the parentheses of the function, after the name of the parameter, assign the default value to it. Here is an example:

public double OriginalPrice;

double CalculatePriceAfterDiscount(double discountRate = 50)
{
    return OriginalPrice - (OriginalPrice * discountRate / 100m);
}

When calling the function, you can pass a value for the argument as we have dove so far. If you want to use the default value, omit passing the argument. Here is an example:

#include <iostream>
using namespace std;

double originalPrice;

double CalculatePriceAfterDiscount(double discountRate = 50)
{
    return originalPrice - (originalPrice * discountRate / 100);
}

int main()
{
    double discountRate = 20.00; // 20%
    originalPrice = 198.75;

    double priceAfterDiscount = CalculatePriceAfterDiscount();

    cout << "Fun Department Store\n";
    cout << "=========================\n";
    cout << "Orignial Price:  " << originalPrice << endl;
    cout << "Discount Rate:   " << discountRate << "%\n";
    cout << "-------------------------\n";
    cout << "Marked Price:    " << priceAfterDiscount << endl;
    cout << "=========================" << endl;
}

This would produce:

Fun Department Store
=========================
Orignial Price:  198.75
Discount Rate:   20%
-------------------------
Marked Price:    99.375
=========================

Press any key to close this window . . .

This code would produce the same result as the previous one. Notice that the parentheses of the function are empty, which means that the argument was not passed.

A Function With Many Parameters

Creating a Function With Many Parameters

A function can use many parameters, as many as you judge them necessary. When creating the function, in its parentheses, provide each parameter by its data type and a name. The parameters are separated by commas. The parameters can be of the same type. Here is an example:

void ShowTimeWorked(string startTime, string endTime)
{

}

The parameters can also be of different types. Here is an example of a function that uses 3 parameters:

void ShowTimeWorked(string startTime, int timeWorked, string endTime)
{

}

As mentioned earlier, you don't have to use a parameter in the body of the function if you don't have use for it. Otherwise, in the body of the function, you can use the parameters any appropriate way you want.

Practical LearningPractical Learning: Creating Functions With Many Parameters

Calling a Function of Many Parameters

When calling a function that uses many parameters, you must provide a value for each parameter in the order the parameters appear in the parentheses. You can provide the value of each parameter. Here is an example:

#include <iostream>
using namespace std;

string Identity(char type)
{
    auto value = "Unknown";

    if (type == 'C')
        value = "Condominium";
    else if (type == 'T')
        value = "Townhouse";
    else if (type == 'S')
        value = "Single Family";

    return value;
}

void PresentListing(int propNbr, int beds, float baths, long value, char type)
{
    cout << "\nProperty #:     " << propNbr;
    cout << "\nProperty Type:  " << Identity(type);
    cout << "\nBedrooms:       " << beds;
    cout << "\nBathrooms:      " << baths;
    cout << "\nMarket Value:   " << value;
}

int main()
{
    cout << "=//= Altair Realtors =//=\n";
    cout << "-------------------------------\n";
    cout << "Property Description\n";
    PresentListing(825308, 2, 1, 227775, 'C');
    cout << endl << "==============================\n";
}

This would produce:

=//= Altair Realtors =//=
-------------------------------
Property Description

Property #:     825308
Property Type:  Condominium
Bedrooms:       2
Bathrooms:      1
Market Value:   227775
==============================

Press any key to close this window . . .

Or you can pass an argument using a variable. Once again, the name of the variable and the parameter can be different. The important aspect is that the variable and the parameter must use the same or copatible type.

Author Note

New Convention:

From now on, in our lessons, we may write "The syntax of this function is" (or something to that effect):

return-type function-name(parameter(s));

This means that we are referring to the function function-name that uses the parameter(s) specified. We will also provide (or review) the return type of the function.

Practical LearningPractical Learning: Calling a Function of Many Parameters

  1. Change the document as follows:
    #include <iostream>
    using namespace std;
    
    void Announce()
    {
        cout << "=========================================================");
        cout << " - Amazing DeltaX - State Income Tax -");
        cout << "---------------------------------------------------------");
        cout << "          -=- Georgia -=-");
        cout << "=========================================================");
    }
    
    string GetFilingStatus()
    {
        cout << "Filing Status");
        cout << "i - Single");
        cout << "s - Married Filing Separate");
        cout << "j - Married Filing Joint or Head of Household");
        cout << "Enter Filing Status: ");
        string answer = ReadLine();
    
        if ((answer == "s") || (answer == "S"))
            return "Married Filing Separate";
        else if ((answer == "j") || (answer == "J"))
            return "Married Filing Joint or Head of Household";
        else // if ((answer == "i") || (answer == "I"))
            return "Single";
    }
    
    double GetGrossSalary()
    {
        cout << "Gross Salary:        ");
        double grossSalary = double.Parse(ReadLine());
    
        return grossSalary;
    }
    
    double CalculateTaxAmount(string status, double salary)
    {
        double taxRate, addedAmount;
    
        // Georgia
        if (status == "Married Filing Joint or Head of Household")
        {
            if (salary >= 10000)
            {
                addedAmount = 340;
                taxRate = 5.75;
            }
            else if (salary >= 7000)
            {
                addedAmount = 190;
                taxRate = 5.00;
            }
            else if (salary >= 5000)
            {
                addedAmount = 110;
                taxRate = 4.00;
            }
            else if (salary >= 3000)
            {
                addedAmount = 50;
                taxRate = 3.00;
            }
            else if (salary >= 1000)
            {
                addedAmount = 10;
                taxRate = 2.00;
            }
            else // if salary < 1000:)
            {
                addedAmount = 0;
                taxRate = 1.00;
            }
        }
        else if (status == "Married Filing Separate")
        {
            if (salary >= 5000)
            {
                addedAmount = 170;
                taxRate = 5.75;
            }
            else if (salary >= 3500)
            {
                addedAmount = 95;
                taxRate = 5.00;
            }
            else if (salary >= 2500)
            {
                addedAmount = 55;
                taxRate = 4.00;
            }
            else if (salary >= 1500)
            {
                addedAmount = 25;
                taxRate = 3.00;
            }
            else if (salary >= 500)
            {
                addedAmount = 5;
                taxRate = 2.00;
            }
            else // if( salary < 1000)
            {
                addedAmount = 0;
                taxRate = 1.00;
            }
        }
        else // "Single";
        {
            if (salary >= 7000)
            {
                addedAmount = 230;
                taxRate = 5.75;
            }
            else if (salary >= 5250)
            {
                addedAmount = 143;
                taxRate = 5.00;
            }
            else if (salary >= 3_750)
            {
                addedAmount = 83;
                taxRate = 4.00;
            }
            else if (salary >= 2250)
            {
                addedAmount = 38;
                taxRate = 3.00;
            }
            else if (salary >= 750)
            {
                addedAmount = 8;
                taxRate = 2.00;
            }
            else // if salary < 750)
            {
                addedAmount = 0;
                taxRate = 1.00;
            }
        }
    
        return addedAmount + (salary * taxRate / 100.00);
    }
    
    double CalculateNetPay(double salary, double tax)
    {
        return salary - tax;
    }
    
    Announce();
    
    cout << "Enter the information for tax preparation");
    string filingStatus = GetFilingStatus();
    double grossSalary = GetGrossSalary();
    
    double taxAmount = CalculateTaxAmount(filingStatus, grossSalary);
    double net_pay = CalculateNetPay(grossSalary, taxAmount);
    
    Announce();
    
    cout << $"Gross Salary:  {grossSalary:f}");
    cout << $"Filing Status: {filingStatus}");
    cout << "---------------------------------------------------------");
    cout << $"Tax Amount:    {taxAmount:f}");
    cout << $"Net Pay:       {net_pay:f}");
    cout << "=========================================================");
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. For the Filing Status, type J and press Enter
  4. For the Gross Salary, type 1688.85 and press Enter:
    =========================================================
     - Amazing DeltaX - State Income Tax -
    ---------------------------------------------------------
              -=- Georgia -=-
    =========================================================
    Enter the information for tax preparation
    Filing Status
    i - Single
    s - Married Filing Separate
    j - Married Filing Joint or Head of Household
    Enter Filing Status: J
    Gross Salary:        1688.85
    =========================================================
     - Amazing DeltaX - State Income Tax -
    ---------------------------------------------------------
              -=- Georgia -=-
    =========================================================
    Gross Salary:  1688.85
    Filing Status: Married Filing Joint or Head of Household
    ---------------------------------------------------------
    Tax Amount:    43.78
    Net Pay:       1645.07
    =========================================================
    Press any key to close this window . . .
  5. Press T to close the window and return to your programming environment

Parameters with Default Values

You can create a function that uses many parameters and some or all of those parameters can have default values. If a function uses more than one parameter, you can provide a default value for each and select which ones would have default values. If you want all parameters to have default values, when defining the function, type each name followed by = and followed by the desired value. Here is an example:

#include <iostream>
using namespace std;

double CalculatePriceAfterDiscount(double price = 200.00, double tax = 5.75, double discount = 50.00)
{
    double markedPrice;

    double afterDiscount = price * discount / 100.00;
    double taxValue = afterDiscount * tax / 100.00;
    markedPrice = afterDiscount + taxValue;

    return markedPrice;
}

int main()
{
    double discountRate = 20.00; // 20%
    double originalPrice = 198.75;

    double priceAfterDiscount = CalculatePriceAfterDiscount();

    cout << "Fun Department Store\n";
    cout << "=========================\n";
    cout << "Orignial Price:  " << originalPrice << endl;
    cout << "Discount Rate:   " << discountRate << "%\n";
    cout << "-------------------------\n";
    cout << "Marked Price:    " << priceAfterDiscount << endl;
    cout << "=========================" << endl;
}

This would produce:

Fun Department Store
=========================
Orignial Price:  198.75
Discount Rate:   20%
-------------------------
Marked Price:    105.75
=========================

Press any key to close this window . . .

Rules on Parameters With Optional Values

If a function uses more than one parameter and you would like to provide default values for those parameters, the order of appearance of the arguments is important:

Deferred Definition

You already know that you can declare a function before defining it. If the function uses many parameters, when declaring it, provide the data type of each parameter. Here is an example:

#include <iostream>
using namespace std;

string Identity(char type);
void PresentListing(int propNbr, int beds, float baths, long value, char type);

int main()
{
    cout << "=//= Altair Realtors =//=";
    cout << endl << "==============================\n";
    cout << "Property Description\n";
    cout << "------------------------------";
    PresentListing(925739, 6, 4.5, 1186495, 'U');
    cout << endl << "==============================\n";
}

string Identity(char type)
{
    auto value = "Unknown";

    if (type == 'C')
        value = "Condominium";
    else if (type == 'T')
        value = "Townhouse";
    else if (type == 'S')
        value = "Single Family";

    return value;
}

void PresentListing(int propNbr, int beds, float baths, long value, char type)
{
    cout << "\nProperty #:     " << propNbr;
    cout << "\nProperty Type:  " << Identity(type);
    cout << "\nBedrooms:       " << beds;
    cout << "\nBathrooms:      " << baths;
    cout << "\nMarket Value:   " << value;
}

This would produce:

=//= Altair Realtors =//=
==============================
Property Description
------------------------------
Property #:     925739
Property Type:  Unknown
Bedrooms:       6
Bathrooms:      4.5
Market Value:   1186495
==============================

Press any key to close this window . . .

When declaring the function, you don't have to provide a name for the parameters; just the data type is enough, but you must provide a name for each parameter when defining the function. Consider the following example:

#include <iostream>
using namespace std;

string Identity(char type);
void PresentListing(int, int, float, long, char);

int main()
{
    cout << "=//= Altair Realtors =//=";
    cout << endl << "==============================\n";
    cout << "Property Description\n";
    cout << "------------------------------";
    PresentListing(925739, 6, 4.5, 1186495, 'U');
    cout << endl << "==============================\n";
}

. . .

void PresentListing(int propNbr, int beds, float baths, long value, char type)
{
    . . .
}

Previous Copyright © 1998-2026, FunctionX Sunday 29 June 2025, 12:10 Next