0% found this document useful (0 votes)
25 views11 pages

Lecture 6 Argument Parameters-1

Uploaded by

vicentmachicho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views11 pages

Lecture 6 Argument Parameters-1

Uploaded by

vicentmachicho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

LECTURE EIGHT

Arguments – Parameters

In order to carry its assignment, a function might be supplied something. For example,
when a function is used to calculate the area of a square, you have to supply the side of the
square, then the function will work from there. On the other hand, a function used to get a
student’s first name may not have a need; its job would be to supply or return something.

Some functions have needs and some do not. The needs of a function are provided
between parentheses. These needs could be as varied as possible. If a function does not
have a need, leave its parentheses empty.

Some functions will have only one need, some others will have many. A function’s need is
called an Argument. If a function has a lot of needs, these are its arguments.

The argument is a valid variable and is defined by its data type and a name. For example,
if a function is supposed to calculate the area of a square and it is expecting to receive the
side of the square, you can declare it as

double CalculateArea(double Side);

A function used to get a student’s first name could be declared as:

string FirstName();

Here are examples of declaring functions; some take arguments, some don’t:

double CalculateArea(double Side);


char Answer();
void Message(float Distance);
bool InTheBox(char Mine);
string StudentName();
double RectangleArea(double Length, double Width);
void DefaultBehavior(int Key, double Area, char MI, float Ter);

Techniques of Passing Arguments

1
In order to perform its assignment, a function may need arguments. Any function that
wants to use the result of another function must supply the other function’s required
arguments, if any. When declaring a function that uses arguments, specify each argument
with a data type and a name.

Passing Arguments by Value

To use a function inside another function, that is, to call a function from another function,
specify the name of the function and its list of arguments (if any) inside of parentheses;
only the name of each argument is needed. You can declare a function like this:

Example

#include <iostream.h>

int sum(int a, int b=20)

int result;

result = a + b;

return (result);

int main ()

int a = 100;

int b = 200;

int result;

// calling a function to add the values.

result = sum(a, b);

cout << "Total value is :" << result << endl;

return 0;}

When the above code is compiled and executed, it produces the following result:

Total value is :300

Example 2

2
Imagine you want to write a function that would calculate an item’s purchase price based
on the item’s store price added the tax. The tax rate is a percentage value. This means that
a tax rate set at 7.50% in C++ terms is equal to 0.075 (because 7.50/100 = 0.075). The tax
amount collected on a purchase is taken from an item’s price; its formula is:

TaxRate
Tax Amount = Item Price * 100

The formula of calculating the final price of an item is:

Final Price = Item Price + Tax Amount

Here is an example:

#include <iostream.h>

int main()
{
double itemPrice, taxRate;
double PurchasePrice(double itemPrice, double taxRate);

cout << "Enter the price of the item: ";


cin >> itemPrice;
cout << "Enter the tax rate: ";
cin >> taxRate;
cout << "\nThe final price is: " << PurchasePrice(itemPrice, taxRate);

cout << "\n\n";


return 0;
}

double PurchasePrice(double itemPrice, double taxRate)


{
double price;

price = itemPrice + (itemPrice * taxRate / 100);


return price;
}
Here is an example of running the program:

Enter the price of the item: 125.95


Enter the tax rate: 5.75

The final price is: 133.192

Passing Arguments by Reference

3
When you declare a variable in a program, the compiler reserves an amount of space for
that variable. If you need to use that variable somewhere in your program, you call it and
make use of its value. There are two major issues related to a variable: its value and its
location in the memory.

The location of a variable in memory is referred to as its address.

If you supply the argument using its name, the compiler only makes a copy of the
argument’s value and gives it to the calling function. Although the calling function
receives the argument’s value and can use in any way, it cannot (permanently) alter it. C++
allows a calling function to modify the value of a passed argument if you find it necessary.
If you want the calling function to modify the value of a supplied argument and return
the modified value, you should pass the argument using its reference.

To pass an argument as a reference, when declaring the function, precede the argument
name with an ampersand “&”. You can pass 0, one, or more arguments as reference in the
program or pass all arguments as reference. The decision as to which argument(s) should
be passed by value or by reference is based on whether or not you want the called function
to modify the argument and permanently change its value.

Here are examples of passing some arguments by reference:

void Area(double &side); // The argument is passed by reference


bool Decision(char &answer, int age); // One argument is passed by reference

// All arguments are passed by reference


float Purchase(float &discountPrice, float &newDiscount, char &commission);
You add the ampersand when declaring a function and/or when defining it. When
calling the function, supply only the name of the referenced argument(s). The above would
be called with:

Area(side);
Decision(answer, Age);
Purchase(discountPrice, newDiscount, commission);
Imagine that you write a function that calculates employees weekly salary provided the
total weekly hours and hourly rate. To illustrate our point, we will see how or whether one
function can modify a salary of an employee who claims to have worked more than the
program displays. The starting regular program would be as follows:

#include <iostream.h>
4
int main()
{
float hours, rate, wage;
void Earnings(float h, float r);

cout << "Enter the total Weekly hours: ";


cin >> hours;
cout << "Enter the employee's hourly rate: ";
cin >> rate;

cout << "\nIn the main() function,";


cout << "\n\tWeekly Hours = " << hours;
cout << "\n\tSalary = $" << rate;
cout << "\n\tWeekly Salary: $" << hours * rate;
cout << "\nCalling the Earnings() function";

Earnings(hours, rate);

cout << "\n\nAfter calling the Earnings() function, "


<< "in the main() function,";
cout << "\n\tWeekly Hours = " << hours;
cout << "\n\tSalary = " << rate;
cout << "\n\tWeekly Salary: " << hours * rate;

return 0;
}

void Earnings(float thisWeek, float salary)


{
cout << "\n\nIn the Earnings() function,";
cout << "\n\tWeekly Hours = " << thisWeek;
cout << "\n\tSalary = " << salary;
cout << "\n\tWeekly Salary= " << thisWeek * Salary;
}
If you test the program by typing 32 for the weekly hours and 6.45 for the salary, you
would notice the weekly values are the same.

Imagine that the employee claims to have worked 42 hours instead of the passed weekly
hours. You could create the following function to find out.

void Earnings(float thisWeek, float salary)


{
thisWeek = 42;

cout << "\n\nIn the Earnings() function,";


cout << "\n\tWeekly Hours = " << thisWeek;
5
cout << "\n\tSalary = " << salary;
cout << "\n\tWeekly Salary= " << thisWeek * Salary;
}
If you test the program with a weekly hours value of 35.50 and a salary of 8.50, you would
notice that the weekly salary is different inside of the Earnings() function but is kept the
same in main(), before and after the Earnings() function. As an example of passing an
argument by reference, you could modify the declaration of the Earnings() function inside
of the main() function as follows:

void Earnings(float &h, float r);


If you want a calling function to modify the value of an argument, you should supply its
reference and not its value. You could change the function as follows:

void Earnings(float &thisWeek, float salary)


{
thisWeek = 42;

cout << "\n\nIn the Earnings() function,";


cout << "\n\tWeekly Hours = " << thisWeek;
cout << "\n\tSalary = " << salary;
cout << "\n\tWeekly Salary= " << thisWeek * Salary;
}

Default Arguments

Whenever a function takes an argument, that argument is required. If the calling function
does not provide the (required) argument, the compiler would throw an error.

Imagine you write a function that will be used to calculate the final price of an item after
discount. The function would need the discount rate in order to perform the calculation.
Such a function could look like this:

double CalculateNetPrice(double discountRate)


{
double OrigPrice;

cout << "Please enter the original price: ";


cin >> origPrice;

return origPrice - (origPrice * discountRate / 100);


}
Since this function expects an argument, if you do not supply it, the following program
would not compile:

#include <iostream.h>
6
double CalculateNetPrice(double discountRate)
{
double origPrice;

cout << "Please enter the original price: ";


cin >> origPrice;

return origPrice - (origPrice * discountRate / 100);


}

int main()
{
double finalPrice;
double discount = 15; // That is 25% = 25

finalPrice = CalculateNetPrice(discount);

cout << "\nFinal Price = " << finalPrice << "\n\n";

return 0;
}

Therefore, instead of supplying an argument all the time, C++ allows you to define an
argument whose value would be used whenever the function is not provided with the
argument.

To give a default value to an argument, when declaring the function, type the name of
the argument followed by the assignment operator “=”, followed by the default value.
The CalculateNetPrice() function, with a default value, could be defined as:

#include <iostream.h>

double CalculateNetPrice(double discountRate = 25)


{
double origPrice;

cout << "Please enter the original price: ";


cin >> origPrice;

return origPrice - (origPrice * discountRate / 100);


}

7
int main()
{
double finalPrice;

finalPrice = calculateNetPrice();

cout << "\nFinal Price = " << finalPrice << "\n\n";

return 0;
}
If a function takes more than one argument, you can provide a default argument for each
and select which ones would have default values. If you want all arguments to have default
values, when defining the function, type each name followed by = followed by the desired
value. Here is an example:

#include <iostream.h>

double CalculateNetPrice(double tax = 5.75, double discount = 25,


double origPrice = 245.55)
{
double discountValue = origPrice * discount / 100;
double taxValue = tax / 100;
double netPrice = origPrice - discountValue + taxValue;

cout << "Original Price: $" << origPrice << endl;


cout << "Discount Rate: " << discount << "%" << endl;
cout << "Tax Amount: $" << tax << endl;

return netPrice;
}

int main()
{
double finalPrice;

finalPrice = CalculateNetPrice();
cout << "Final Price: $" << finalPrice << "\n\n";

return 0;
}
Here is the result produced:

Original Price: $245.55


Discount Rate: 25%
Tax Amount: $5.75

8
Final Price: $184.22

If a function receives more than one argument and you would like to provide default
values for those parameters, the order of appearance of the arguments is very important.

 If a function takes two arguments, you can declare it with default values. If you
want to provide a default value for only one of the arguments, the argument that
would have a default value must be the second in the list.
 Here is an example:
double CalculatePrice(double Tax, double Discount = 25);
When calling such a function, if you supply only one argument, the compiler would
assign its value to the first parameter in the list and ignore assigning a value to the
second (because the second already has a (default) value):
#include <iostream.h>

double CalculateNetPrice(double tax, double discount = 25)


{
double origPrice;

cout << "Enter the original price of the item: ";


cin >> origPrice;

double discountValue = origPrice * discount / 100;


double taxValue = tax / 100;
double netPrice = origPrice - discountValue + taxValue;

return NetPrice;
}

int main()
{
double taxRate = 5.50; // = 5.50%
double finalPrice;

finalPrice = CalculateNetPrice(taxRate);

cout << "\nFinal Price = " << finalPrice << "\n\n";

return 0;
}

 If the function receives more than two arguments and you would like only some of
those arguments to have default values, the arguments that would have default
values must be at the end (right side) of the list. Regardless of how many arguments
would or would not have default values, start the list of arguments without those
9
that would not use default values.

Constant Arguments

When a function receives an argument, it performs one of two actions with regards to the
value of the argument; it might modify the value itself or only use the argument to
modify another argument or another of its own variables. If you know that the function
is not supposed to alter the value of an argument, you should let the compiler know.
This is a safeguard that serves at least two purposes. First, the compiler will make sure
that the argument supplied stays intact; if the function tries to modify the argument, the
compiler would throw an error, letting you know that an undesired operation took place.
Second, this speeds up execution.

To let the compiler know that the value of an argument must stay constant, use the const
keyword before the data type of the argument.

For example, if you declare a function like void Area(const string Side), the Area() function
cannot modify the value of the Side argument. Consider a function that is supposed to
calculate and return the perimeter of a rectangle if it receives the length and the width from
another function, namely main(). Here is a program that would satisfy the operation (notice
the Perimeter() function that takes two arguments):

#include <iostream.h>

float Perimeter(float l, float w)


{
double p;

p = 2 * (l + w);
return p;
}

int main()
{
float length, width;

cout << "Rectangle dimensions.\n";


cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "\nThe perimeter of the rectangle is: "
<< Perimeter(length, width) << "\n\n";

return 0;

10
}

This would produce:

Rectangle dimensions.
Enter the length: 35.55
Enter the width: 28.75

The perimeter of the rectangle is: 2044.12


As you can see, the Perimeter() function does not change the values of the length or the
width. To reinforce the purpose of the assignment, you should make this clear to the
compiler. To make the length and the width arguments constant, you would change the
declaration of the Perimeter() function as follows:

float Perimeter(const float l, const float w);


You can make just one or more arguments constants, and there is no order on which
arguments can be made constant.

11

You might also like