Topics of Functions
Topics of Functions
Techniques of Passing Arguments
Introduction
When calling a function that takes one or more arguments, we provide the necessary value(s) for the parameter(s). This is because an argument is always required and the calling function must provide a valid value when calling such a function. This technique of providing a value for the argument is referred to as passing an argument by value. Here are examples:
#include <iostream> using namespace std; double Subtract(double a, double b); double CalculateDiscount(double price, double rate); int main() { double cost = 149.95; int dRate = 20; double discount = CalculateDiscount(cost, dRate); double markedValue = Subtract(cost, discount); cout << "Fun Department Store"; cout << endl << "==========================="; cout << endl << "Orignial Price: " << cost; cout << endl << "Discount Rate: " << dRate << '%'; cout << endl << "---------------------------"; cout << endl << "Discount Amount: " << discount; cout << endl << "Marked Price: " << markedValue; cout << endl << "==========================="; } double Subtract(double a, double b) { return a - b; } double CalculateDiscount(double price, double rate) { return price * rate / 100.00; }
This would produce:
Fun Department Store =========================== Orignial Price: 149.95 Discount Rate: 20% --------------------------- Discount Amount: 29.99 Marked Price: 119.96 =========================== Press any key to close this window . . .
Practical Learning: Introducing Parameters
#include <iostream>
using namespace std;
int main()
{
PreparePayroll();
}
string GetFirstName()
{
cout << "FUN DEPARTMENT STORE");
cout << "=======================================================");
cout << "Payroll Preparation");
cout << "-------------------------------------------------------");
cout << "Enter the following pieces of information");
cout << "-------------------------------------------------------");
cout << "Employee Information");
cout << "-------------------------------------------------------");
cout << "First Name: ");
string result = ReadLine();
return result;
}
string GetLastName()
{
cout << "Last Name: ");
string result = ReadLine();
return result;
}
double GetBaseRate()
{
cout << "Hourly Salary: ");
double wages = double.Parse(ReadLine());
return wages;
}
double GetMondayTimeWorked()
{
cout << "-------------------------------------------------------");
cout << "Time worked");
cout << "-------------------------------------------------------");
cout << "Monday: ");
double time = double.Parse(ReadLine());
return time;
}
double GetTuesdayTimeWorked()
{
cout << "Tuesday: ");
double time = double.Parse(ReadLine());
return time;
}
double GetWednesdayTimeWorked()
{
cout << "Wednesday: ");
double time = double.Parse(ReadLine());
return time;
}
double GetThursdayTimeWorked()
{
cout << "Thursday: ");
double time = double.Parse(ReadLine());
return time;
}
double GetFridayTimeWorked()
{
cout << "Friday: ");
double time = double.Parse(ReadLine());
return time;
}
double Add2(double m, double n)
{
return m + n;
}
double Add5(double a, double b, double c, double d, double e)
{
return a + b + c + d + e;
}
Practical Learning: Passing Parameters IN
using static System.Console;
PreparePayroll();
// -------------------------------------------------------
string GetFirstName()
{
cout << "FUN DEPARTMENT STORE");
cout << "=======================================================");
cout << "Payroll Preparation");
cout << "-------------------------------------------------------");
cout << "Enter the following pieces of information");
cout << "-------------------------------------------------------");
cout << "Employee Information");
cout << "-------------------------------------------------------");
cout << "First Name: ");
string result = ReadLine();
return result;
}
string GetLastName()
{
cout << "Last Name: ");
string result = ReadLine();
return result;
}
double GetBaseRate()
{
cout << "Hourly Salary: ");
double wages = double.Parse(ReadLine());
return wages;
}
double GetMondayTimeWorked()
{
cout << "-------------------------------------------------------");
cout << "Time worked");
cout << "-------------------------------------------------------");
cout << "Monday: ");
double time = double.Parse(ReadLine());
return time;
}
double GetTuesdayTimeWorked()
{
cout << "Tuesday: ");
double time = double.Parse(ReadLine());
return time;
}
double GetWednesdayTimeWorked()
{
cout << "Wednesday: ");
double time = double.Parse(ReadLine());
return time;
}
double GetThursdayTimeWorked()
{
cout << "Thursday: ");
double time = double.Parse(ReadLine());
return time;
}
double GetFridayTimeWorked()
{
cout << "Friday: ");
double time = double.Parse(ReadLine());
return time;
}
double Add2(in double m, in double n)
{
return m + n;
}
double Add5(in double a, in double b, in double c, in double d, in double e)
{
return a + b + c + d + e;
}
double CalculateRegularTime(double time)
{
double result = time;
if (time > 40.00)
{
result = 40.00;
}
return result;
}
double CalculateRegularPay(double sal, double time)
{
double result = sal * time;
if (time > 40.00)
{
result = sal * 40.00;
}
return result;
}
double CalculateOvertime(double time)
{
double result = 0.00;
if (time > 40.00)
{
result = time - 40.00;
}
return result;
}
double CalculateOvertimePay(double sal, double time, double over)
{
double result = 0.00;
if (time > 40.00)
{
result = sal * 1.50 * over;
}
return result;
}
void PreparePayroll()
{
string firstName = GetFirstName();
string lastName = GetLastName();
double hSalary = GetBaseRate();
double mon = GetMondayTimeWorked();
double tue = GetTuesdayTimeWorked();
double wed = GetWednesdayTimeWorked();
double thu = GetThursdayTimeWorked();
double fri = GetFridayTimeWorked();
double timeWorked = Add5(mon, tue, wed, thu, fri);
double regularTime = CalculateRegularTime(timeWorked);
double regularPay = CalculateRegularPay(hSalary, timeWorked);
double overtime = CalculateOvertime(timeWorked);
double overtimePay = CalculateOvertimePay(hSalary, timeWorked, overtime);
double weeklyPay = Add2(regularPay, overtimePay);
cout << "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
cout << "FUN DEPARTMENT STORE");
cout << "=======================================================");
cout << "Payroll Evaluation");
cout << "=======================================================");
cout << "Employee Information");
cout << "-------------------------------------------------------");
cout << "Full Name: {firstName} {lastName}");
cout << "Hourly Salary: {hSalary:f}");
cout << "=======================================================");
cout << "Time Worked Summary");
cout << "--------+---------+-----------+----------+-------------");
cout << " Monday | Tuesday | Wednesday | Thursday | Friday");
cout << "--------+---------+-----------+----------+-------------");
cout << " {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}");
cout << "========+=========+===========+==========+=============");
cout << " Pay Summary");
cout << "-------------------------------------------------------");
cout << " Time Pay");
cout << "-------------------------------------------------------");
cout << " Regular: {regularTime:f} {regularPay:f}");
cout << "-------------------------------------------------------");
cout << " Overtime: {overtime:f} {overtimePay:f}");
cout << "=======================================================");
cout << " Net Pay: {weeklyPay:f}");
cout << "=======================================================");
}FUN DEPARTMENT STORE
=======================================================
Payroll Preparation
-------------------------------------------------------
Enter the following pieces of information
-------------------------------------------------------
Employee Information
-------------------------------------------------------
First Name: Michael
Last Name: Carlock
Hourly Salary: 28.25
-------------------------------------------------------
Time worked
-------------------------------------------------------
Monday: 7
Tuesday: 8
Wednesday: 6.5
Thursday: 8.5
Friday: 6.5
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
FUN DEPARTMENT STORE
=======================================================
Payroll Evaluation
=======================================================
Employee Information
-------------------------------------------------------
Full Name: Michael Carlock
Hourly Salary: 28.25
=======================================================
Time Worked Summary
--------+---------+-----------+----------+-------------
Monday | Tuesday | Wednesday | Thursday | Friday
--------+---------+-----------+----------+-------------
7.00 | 8.00 | 6.50 | 8.50 | 6.50
========+=========+===========+==========+=============
Pay Summary
-------------------------------------------------------
Time Pay
-------------------------------------------------------
Regular: 36.50 1031.12
-------------------------------------------------------
Overtime: 0.00 0.00
=======================================================
Net Pay: 1031.12
=======================================================
Press any key to close this window . . .Passing an Argument by Value
When calling a function that takes at least one argument, if you supply an argument using its name, the compiler only makes a copy of the argument's value and passes it to the called function. Although the called function receives the argument's value and can use it in any way it wants, it cannot change that value. This technique of passing an argument is referred to as passing an argument by value.
Passing an Argument by Reference
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 use 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 it 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 an argument by reference:
void GetMiles(int& miles)
{
}
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). Here are examples:
#include <iostream> using namespace std; void GetMiles(int& miles) { cout << "Miles Driven: "; cin >> miles; } void GetWorkRate(double& pieceworkRate) { cout << "Piecework Rate: "; cin >> pieceworkRate; } int main() { int a; double b; GetMiles(a); GetWorkRate(b); cout << "========================="; cout << "\n - Piece Work Delivery -"; cout << "\n========================="; cout << "\nMiles Driven: " << a; cout << "\nPiecework Rate: " << b; cout << "\n========================="; }
Introduction
The syntax of a function is a combination of its name and the type(s) of its parameter(s), if any. The return type and the symbols (such as the parentheses and the curly brackets) are not part of the syntax of a function. Since some functions don't take any parameter, the syntax of such functions is only the name of the function. Consider the following function:
void Consist()
{
}
The syntax of that function can be represented as follows:
Consist
Consider the following function:
double Consist()
{
}
The syntax of that function can also be represented as follows:
Consist
Notice that both functions use the same name. Also notice their return types, void and double. Regardless of the return types, since those functions use the same name and they don't use any parameter, they have the same syntax. Consider a function as follows:
int Consist(string characters)
{
}
If a function uses one parameter, its syntax consists of its name and the data type of the parameter, as in:
method-name#parameter-type
As a result, the syntax of the above function is:
Count#string
If a function uses two parameters, its syntax consists of its name and the data types of the parameters in the order they appear, as in:
method-name#parameter_1-type#parameter_2-type
If a function uses more parameters, its syntax consists of its name and the data types of the parameters in the order they appear, as in:
method-name#parameter_1-type#parameter_2-type#parameter_n-type
Practical Learning: Introducing Function Overloading
namespace ElementaryAlgebra1.Models
{
public class Calculations
{
public int Add(int a, int b)
{
return a + b;
}
}
}Overloading a Function
Function overloading is the ability to have two or more functions with the same name. The primary rule (probably the only rule) is that the overloaded functions cannot have the same syntax.
To perform function overloading, each version of the overloaded function must have a different syntax. Consider the following code:
// Square double CalculateArea(double side) { return side * side; } // Circle double CalculateArea(double radius) { return radius * radius * 3.14159; }
That code will produce an error because both functions have the same syntax. There are two main options you can use to solve function overloading issues. One of the solutions to perform function overloading is that the parameters of the functions must different data types. Here is an example:
double CalculateBiweeklySalary(double yearlySalary) { return yearlySalary / 24.00; } // A full-time employee with a fixed yearly salary double CalculateBiweeklySalary(string monthlySalary) { double salary = double.Parse(monthlySalary); return monthlySalary / 2.00; }
Another option is that each function can use a different number of parameters. Based on this, if you insist on having various methods that use the exact same syntax, simply add an extra parameter to some of them and don't use that extra parameter in the function.
Practical Learning: Overloading a Method
int Add(int a, int b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
public int Add(int a, int b, int c, int d)
{
return a + b + c + d;
}void Display(int x, int y)
{
Calculations cals = new Calculations();
int result = cals.Add(x, y);
cout << "Result: {x} + {y} = {result}");
}
void Display(int x, int y, int z)
{
Calculations cals = new Calculations();
cout << "Result: {x} + {y} + {z} = {cals.Add(x, y, z)}");
}
void Display(int u, int v, int w, int x)
{
Calculations cals = new Calculations();
int result = cals.Add(u, v, w, x);
cout << "Result: {u} + {v} + {w} + {x} = {result}");
}
public void Present()
{
cout << "========================================");
cout << " =-=-= Elementary Operations =-=-=");
cout << "========================================");
cout << "Enter a number: ");
int number1;
cin >> number1;
cout << "Enter another number: ");
int number2;
cin >> number2;
cout << "Enter one more Number: ");
int number3;
cin >> number3;
cout << "Enter one more Number: ");
int number4;
cin >> number4;
cout << "=======================================");
cout << " =-=-= Elementary Operations =-=-=");
cout << "=======================================");
Display(number1, number2);
cout << "---------------------------------------");
Display(x: number1, y: number2, z: number3);
cout << "---------------------------------------");
Display(x: number4, u: number1, w: number3, v: number2);
cout << "=====================================");
}using ElementaryAlgebra1.Models; Presentation pres = new Presentation(); pres.Present();
======================================== =-=-= Elementary Operations =-=-= ======================================== Enter a number: 10482 Enter another number: 836 Enter one more Number: 6297 Enter one more Number: 4 ======================================= =-=-= Elementary Operations =-=-= ======================================= Result: 10482 + 836 = 11318 --------------------------------------- Result: 10482 + 836 + 6297 = 17615 --------------------------------------- Result: 10482 + 836 + 6297 + 4 = 17619 ======================================= Press any key to close this window . . .
Practical Learning: Passing Parameters Out
using static System.Console; PreparePayroll(); // ------------------------------------------------------- void IdentifyEmployee(out string fn, out string ln, out double sal) { cout << "FUN DEPARTMENT STORE"); cout << "======================================================="); cout << "Payroll Preparation"); cout << "-------------------------------------------------------"); cout << "Enter the following pieces of information"); cout << "-------------------------------------------------------"); cout << "Employee Information"); cout << "-------------------------------------------------------"); cout << "First Name: "); fn = ReadLine(); cout << "Last Name: "); ln = ReadLine(); cout << "Hourly Salary: "); sal = double.Parse(ReadLine()); } double GetMondayTimeWorked() { cout << "-------------------------------------------------------"); cout << "Time worked"); cout << "-------------------------------------------------------"); cout << "Monday: "); double time = double.Parse(ReadLine()); return time; } double GetTuesdayTimeWorked() { cout << "Tuesday: "); double time = double.Parse(ReadLine()); return time; } double GetWednesdayTimeWorked() { cout << "Wednesday: "); double time = double.Parse(ReadLine()); return time; } double GetThursdayTimeWorked() { cout << "Thursday: "); double time = double.Parse(ReadLine()); return time; } double GetFridayTimeWorked() { cout << "Friday: "); double time = double.Parse(ReadLine()); return time; } double Add2(in double m, in double n) { return m + n; } double Add5(in double a, in double b, in double c, in double d, in double e) { return a + b + c + d + e; } double CalculateRegularTime(double time) { double result = time; if (time > 40.00) { result = 40.00; } return result; } double CalculateRegularPay(double sal, double time) { double result = sal * time; if (time > 40.00) { result = sal * 40.00; } return result; } double CalculateOvertime(double time) { double result = 0.00; if (time > 40.00) { result = time - 40.00; } return result; } double CalculateOvertimePay(double sal, double time, double over) { double result = 0.00; if (time > 40.00) { result = sal * 1.50 * over; } return result; } void PreparePayroll() { string firstName; string lastName; double hSalary; IdentifyEmployee(out firstName, out lastName, out hSalary); double mon = GetMondayTimeWorked(); double tue = GetTuesdayTimeWorked(); double wed = GetWednesdayTimeWorked(); double thu = GetThursdayTimeWorked(); double fri = GetFridayTimeWorked(); double timeWorked = Add5(mon, tue, wed, thu, fri); double regularTime = CalculateRegularTime(timeWorked); double regularPay = CalculateRegularPay(hSalary, timeWorked); double overtime = CalculateOvertime(timeWorked); double overtimePay = CalculateOvertimePay(hSalary, timeWorked, overtime); double weeklyPay = Add2(regularPay, overtimePay); cout << "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+"); cout << "FUN DEPARTMENT STORE"); cout << "======================================================="); cout << "Payroll Evaluation"); cout << "======================================================="); cout << "Employee Information"); cout << "-------------------------------------------------------"); cout << "Full Name: {firstName} {lastName}"); cout << "Hourly Salary: {hSalary:f}"); cout << "======================================================="); cout << "Time Worked Summary"); cout << "--------+---------+-----------+----------+-------------"); cout << " Monday | Tuesday | Wednesday | Thursday | Friday"); cout << "--------+---------+-----------+----------+-------------"); cout << " {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}"); cout << "========+=========+===========+==========+============="); cout << " Pay Summary"); cout << "-------------------------------------------------------"); cout << " Time Pay"); cout << "-------------------------------------------------------"); cout << " Regular: {regularTime:f} {regularPay:f}"); cout << "-------------------------------------------------------"); cout << " Overtime: {overtime:f} {overtimePay:f}"); cout << "======================================================="); cout << " Net Pay: {weeklyPay:f}"); cout << "======================================================="); }
FUN DEPARTMENT STORE
=======================================================
Payroll Preparation
-------------------------------------------------------
Enter the following pieces of information
-------------------------------------------------------
Employee Information
-------------------------------------------------------
First Name: Catherine
Last Name: Busbey
Hourly Salary: 24.37
-------------------------------------------------------
Time worked
-------------------------------------------------------
Monday: 9.5
Tuesday: 8
Wednesday: 10.5
Thursday: 9
Friday: 8.5
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
FUN DEPARTMENT STORE
=======================================================
Payroll Evaluation
=======================================================
Employee Information
-------------------------------------------------------
Full Name: Catherine Busbey
Hourly Salary: 24.37
=======================================================
Time Worked Summary
--------+---------+-----------+----------+-------------
Monday | Tuesday | Wednesday | Thursday | Friday
--------+---------+-----------+----------+-------------
9.50 | 8.00 | 10.50 | 9.00 | 8.50
========+=========+===========+==========+=============
Pay Summary
-------------------------------------------------------
Time Pay
-------------------------------------------------------
Regular: 40.00 974.80
-------------------------------------------------------
Overtime: 5.50 201.05
=======================================================
Net Pay: 1175.85
=======================================================
Press any key to close this window . . .
Practical Learning: Passing Arguments by Reference
using static System.Console;
PreparePayroll();
// -------------------------------------------------------
void IdentifyEmployee(out string fn, out string ln, out double sal)
{
cout << "FUN DEPARTMENT STORE");
cout << "=======================================================");
cout << "Payroll Preparation");
cout << "-------------------------------------------------------");
cout << "Enter the following pieces of information");
cout << "-------------------------------------------------------");
cout << "Employee Information");
cout << "-------------------------------------------------------");
cout << "First Name: ");
fn = ReadLine();
cout << "Last Name: ");
ln = ReadLine();
cout << "Hourly Salary: ");
sal = double.Parse(ReadLine());
}
void GetTimeWorked(ref double m, ref double t, ref double w, ref double h, ref double f)
{
cout << "-------------------------------------------------------");
cout << "Time worked");
cout << "-------------------------------------------------------");
cout << "Monday: ");
m = double.Parse(ReadLine());
cout << "Tuesday: ");
t = double.Parse(ReadLine());
cout << "Wednesday: ");
w = double.Parse(ReadLine());
cout << "Thursday: ");
h = double.Parse(ReadLine());
cout << "Friday: ");
f = double.Parse(ReadLine());
}
double Add2(in double m, in double n)
{
return m + n;
}
double Add5(in double a, in double b, in double c, in double d, in double e)
{
return a + b + c + d + e;
}
void EvaluateSalary(double time, double sal,
ref double regTime, ref double regPay, ref double overtime, ref double overPay)
{
regTime = time;
regPay = sal * time;
overtime = 0.00;
overPay = 0.00;
if (time > 40.00)
{
regTime = 40.00;
regPay = sal * 40.00;
overtime = time - 40.00;
overPay = sal * 1.50 * overtime;
}
}
void PreparePayroll()
{
string firstName;
string lastName;
double hSalary;
double mon = 0.00;
double tue = 0.00;
double wed = 0.00;
double thu = 0.00;
double fri = 0.00;
double regularTime = 0.00;
double regularPay = 0.00;
double overtime = 0.00;
double overtimePay = 0.00;
IdentifyEmployee(out firstName, out lastName, out hSalary);
GetTimeWorked(ref mon, ref tue, ref wed, ref thu, ref fri);
double timeWorked = Add5(mon, tue, wed, thu, fri);
EvaluateSalary(timeWorked, hSalary,
ref regularTime, ref regularPay, ref overtime, ref overtimePay);
double weeklyPay = Add2(regularPay, overtimePay);
cout << "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
cout << "FUN DEPARTMENT STORE");
cout << "=======================================================");
cout << "Payroll Evaluation");
cout << "=======================================================");
cout << "Employee Information");
cout << "-------------------------------------------------------");
cout << "Full Name: {firstName} {lastName}");
cout << "Hourly Salary: {hSalary:f}");
cout << "=======================================================");
cout << "Time Worked Summary");
cout << "--------+---------+-----------+----------+-------------");
cout << " Monday | Tuesday | Wednesday | Thursday | Friday");
cout << "--------+---------+-----------+----------+-------------");
cout << " {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}");
cout << "========+=========+===========+==========+=============");
cout << " Pay Summary");
cout << "-------------------------------------------------------");
cout << " Time Pay");
cout << "-------------------------------------------------------");
cout << " Regular: {regularTime:f} {regularPay:f}");
cout << "-------------------------------------------------------");
cout << " Overtime: {overtime:f} {overtimePay:f}");
cout << "=======================================================");
cout << " Net Pay: {weeklyPay:f}");
cout << "=======================================================");
}FUN DEPARTMENT STORE
=======================================================
Payroll Preparation
-------------------------------------------------------
Enter the following pieces of information
-------------------------------------------------------
Employee Information
-------------------------------------------------------
First Name: Andrew
Last Name: Sanders
Hourly Salary: 26.97
-------------------------------------------------------
Time worked
-------------------------------------------------------
Monday: 9
Tuesday: 10.50
Wednesday: 7
Thursday: 9.50
Friday: 8.50
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
FUN DEPARTMENT STORE
=======================================================
Payroll Evaluation
=======================================================
Employee Information
-------------------------------------------------------
Full Name: Andrew Sanders
Hourly Salary: 26.97
=======================================================
Time Worked Summary
--------+---------+-----------+----------+-------------
Monday | Tuesday | Wednesday | Thursday | Friday
--------+---------+-----------+----------+-------------
9.00 | 10.50 | 7.00 | 9.50 | 8.50
========+=========+===========+==========+=============
Pay Summary
-------------------------------------------------------
Time Pay
-------------------------------------------------------
Regular: 40.00 1078.80
-------------------------------------------------------
Overtime: 4.50 182.05
=======================================================
Net Pay: 1260.85
=======================================================
Press any key to close this window . . .
Practical Learning: Passing Arguments as Read-Only References
using static System.Console;
PreparePayroll();
// -------------------------------------------------------
void IdentifyEmployee(out string fn, out string ln, out double sal)
{
cout << "FUN DEPARTMENT STORE");
cout << "=======================================================");
cout << "Payroll Preparation");
cout << "-------------------------------------------------------");
cout << "Enter the following pieces of information");
cout << "-------------------------------------------------------");
cout << "Employee Information");
cout << "-------------------------------------------------------");
cout << "First Name: ");
fn = ReadLine();
cout << "Last Name: ");
ln = ReadLine();
cout << "Hourly Salary: ");
sal = double.Parse(ReadLine());
}
void GetTimeWorked(ref double m, ref double t, ref double w, ref double h, ref double f)
{
cout << "-------------------------------------------------------");
cout << "Time worked");
cout << "-------------------------------------------------------");
cout << "Monday: ");
m = double.Parse(ReadLine());
cout << "Tuesday: ");
t = double.Parse(ReadLine());
cout << "Wednesday: ");
w = double.Parse(ReadLine());
cout << "Thursday: ");
h = double.Parse(ReadLine());
cout << "Friday: ");
f = double.Parse(ReadLine());
}
double Add2(ref readonly double m, ref readonly double n)
{
return m + n;
}
double Add5(in double a, in double b, in double c, in double d, in double e)
{
return a + b + c + d + e;
}
void EvaluateSalary(ref readonly double time, ref readonly double sal,
ref double regTime, ref double regPay, ref double overtime, ref double overPay)
{
regTime = time;
regPay = sal * time;
overtime = 0.00;
overPay = 0.00;
if (time > 40.00)
{
regTime = 40.00;
regPay = sal * 40.00;
overtime = time - 40.00;
overPay = sal * 1.50 * overtime;
}
}
void PreparePayroll()
{
string firstName;
string lastName;
double hSalary;
double mon = 0.00;
double tue = 0.00;
double wed = 0.00;
double thu = 0.00;
double fri = 0.00;
double regularTime = 0.00;
double regularPay = 0.00;
double overtime = 0.00;
double overtimePay = 0.00;
IdentifyEmployee(out firstName, out lastName, out hSalary);
GetTimeWorked(ref mon, ref tue, ref wed, ref thu, ref fri);
double timeWorked = Add5(in mon, in tue, in wed, in thu, in fri);
EvaluateSalary(ref timeWorked, ref hSalary,
ref regularTime, ref regularPay, ref overtime, ref overtimePay);
double weeklyPay = Add2(ref regularPay, ref overtimePay);
cout << "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
cout << "FUN DEPARTMENT STORE");
cout << "=======================================================");
cout << "Payroll Evaluation");
cout << "=======================================================");
cout << "Employee Information");
cout << "-------------------------------------------------------");
cout << "Full Name: {firstName} {lastName}");
cout << "Hourly Salary: {hSalary:f}");
cout << "=======================================================");
cout << "Time Worked Summary");
cout << "--------+---------+-----------+----------+-------------");
cout << " Monday | Tuesday | Wednesday | Thursday | Friday");
cout << "--------+---------+-----------+----------+-------------");
cout << " {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}");
cout << "========+=========+===========+==========+=============");
cout << " Pay Summary");
cout << "-------------------------------------------------------");
cout << " Time Pay");
cout << "-------------------------------------------------------");
cout << " Regular: {regularTime:f} {regularPay:f}");
cout << "-------------------------------------------------------");
cout << " Overtime: {overtime:f} {overtimePay:f}");
cout << "=======================================================");
cout << " Net Pay: {weeklyPay:f}");
cout << "=======================================================");
}FUN DEPARTMENT STORE
=======================================================
Payroll Preparation
-------------------------------------------------------
Enter the following pieces of information
-------------------------------------------------------
Employee Information
-------------------------------------------------------
First Name: Jennifer
Last Name: Simms
Hourly Salary: 31.57
-------------------------------------------------------
Time worked
-------------------------------------------------------
Monday: 8
Tuesday: 8
Wednesday: 8
Thursday: 8
Friday: 8
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
FUN DEPARTMENT STORE
=======================================================
Payroll Evaluation
=======================================================
Employee Information
-------------------------------------------------------
Full Name: Jennifer Simms
Hourly Salary: 31.57
=======================================================
Time Worked Summary
--------+---------+-----------+----------+-------------
Monday | Tuesday | Wednesday | Thursday | Friday
--------+---------+-----------+----------+-------------
8.00 | 8.00 | 8.00 | 8.00 | 8.00
========+=========+===========+==========+=============
Pay Summary
-------------------------------------------------------
Time Pay
-------------------------------------------------------
Regular: 40.00 1262.80
-------------------------------------------------------
Overtime: 0.00 0.00
=======================================================
Net Pay: 1262.80
=======================================================
Press any key to close this window . . .Functions and their Arguments
Constant Arguments
When a function receives an argument, it performs one of two actions with regards to the value of the argument; it may 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.
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. Here is a program that would satisfy the operation (notice the Perimeter() function that takes two arguments):
#include <iostream>
using namespace std;
float Perimeter(float l, float w)
{
double p;
p = 2 * (l + w);
return p;
}
int main()
{
float length, width;
cout << "Enter the dimensions of the rectangle.\n";
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "\nThe perimeter of the rectangle is: "
<< Perimeter(length, width) << "\n";
cout << "==========================================";
}
Here is an example of running the program:
Enter the dimensions of the rectangle. Enter the length: 235.59 Enter the width: 97.73 The perimeter of the rectangle is: 666.64 ========================================== Press any key to close this window . . .
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 let the compiler know that the value of a parameter must not change, precede the data type of the parameter with the const keyword. Here are examples:
#include <iostream> using namespace std; float Perimeter(const float l, const float w) { double p; p = 2 * (l + w); return p; } int main() { float length, width; cout << "Enter the dimensions of the rectangle.\n"; cout << "Enter the length: "; cin >> length; cout << "Enter the width: "; cin >> width; cout << "\nThe perimeter of the rectangle is: " << Perimeter(length, width) << "\n"; cout << "=========================================="; }
You can make just one or more arguments constants, and there is no order on which arguments can be made constant. If you decide to declare a function before defining it, apply the const keyword when declaring and when defining the function. Here are examples:
#include <iostream> using namespace std; float Perimeter(const float l, const float w); int main() { float length, width; cout << "Enter the dimensions of the rectangle.\n"; cout << "Enter the length: "; cin >> length; cout << "Enter the width: "; cin >> width; cout << "\nThe perimeter of the rectangle is: " << Perimeter(length, width) << "\n"; cout << "=========================================="; } float Perimeter(const float l, const float w) { double p; p = 2 * (l + w); return p; }
Practical Learning: Using Constant Arguments
#include <iostream>
using namespace std;
// Rectangle
double MomentOfInertia(const double b, const double h)
{
return b * h * h * h / 3;
}
// Semi-Circle
double MomentOfInertia(const double R)
{
const double PI = 3.14159;
return R * R * R * R * PI/ 8;
}
// Triangle
double MomentOfInertia(const double b, const double h, int)
{
return b * h * h * h / 12;
}
int main()
{
double base = 7.74,
height = 14.38,
radius = 12.42;
cout << "Rectangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(base, height) << "mm\n\n";
cout << "Semi-Circle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(radius) << "mm\n\n";
cout << "Triangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(base, height, 1) << "mm\n";
}Rectangle Moment of inertia with regard to the X axis: I = 7671.78mm Semi-Circle Moment of inertia with regard to the X axis: I = 9344.28mm Triangle Moment of inertia with regard to the X axis: I = 1917.95mm
#include <iostream>
using namespace std;
// Rectangle
double MomentOfInertia(const double b, const double h)
{
return b * h * h * h / 3;
}
// Semi-Circle
double MomentOfInertia(const double R)
{
const double PI = 3.14159;
return R * R * R * R * PI/ 8;
}
// Triangle
double MomentOfInertia(const double b, const double h, int)
{
return b * h * h * h / 12;
}
int main()
{
double length, height, radius;
double GetBase();
double GetHeight();
double GetRadius();
cout << "Enter the dimensions of the rectangle\n";
length = GetBase();
height = GetHeight();
cout << "Rectangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Length, Height) << "mm\n\n";
cout << "Enter the radius of the semi-circle\n";
radius = GetRadius();
cout << "Semi-Circle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";
cout << "Enter the dimensions of the triangle\n";
length = GetBase();
height = GetHeight();
cout << "\nTriangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(Length, Height, 1) << "mm\n";
}
double GetBase()
{
double b;
cout << "Enter Base: ";
cin >> b;
return b;
}
double GetHeight()
{
double h;
cout << "Enter Height: ";
cin >> h;
return h;
}
double GetRadius()
{
double r;
cout << "Enter Radius: ";
cin >> r;
return r;
}Enter the dimensions of the rectangle Enter Base: 18.25 Enter Height: 14.15 Rectangle Moment of inertia with regard to the X axis: I = 17235mm Enter the radius of the semi-circle Enter Radius: 15.55 Semi-Circle Moment of inertia with regard to the X axis: I = 22960.5mm Enter the dimensions of the triangle Enter Base: 16.35 Enter Height: 12.75 Triangle Moment of inertia with regard to the X axis: I = 2824.02mm
An Argument as a Constant Reference
If you pass an argument as reference, the compiler would access the argument from its location. The called function can modify the value of the argument. The advantage is that the code execution is faster because the argument is accessed from its address. The disadvantage could be that if the calling function modifies the value of the argument, when the function exits, the value of the argument would have (permanently) changed and the original value would be lost (actually, this can be an advantage as we have learned in the passed). If you do not want the value of the passed argument to be modified, you should pass the argument as a constant reference. When doing this, the compiler would access the argument at its location (or address) but it would make sure that the value of the argument stays intact.
To pass an argument as a constant reference, when declaring the function and when implementing it, type the const keyword, followed by the argument data type, followed by the ampersand operator, followed by a name for the argument. When declaring the function, the name of the argument is optional. Here is a function that receives an argument as a constant reference:
double CalculateNetPrice(const double& tax)
{
double original;
const double discount = 25;
Original = GetOriginalPrice();
double discountValue = original * discount / 100;
double taxValue = tax / 100;
double netPrice = original - discountValue + taxValue;
return NetPrice;
}
You can mix arguments passed by value, those passed as reference, those passed by constant, and those passed by constant references. You will decide, based on your intentions, to apply whatever technique suits your scenario.
The following program illustrates the use of various techniques of passing arguments:
#include <iostream>
using namespace std;
// Passing an argument by reference
void GetOriginalPrice(double& originalPrice)
{
cout << "Enter the original price of the item: $";
cin >> originalPrice;
}
// Passing an argument as a constant reference
// Passing arguments by value
double CalculateNetPrice(const double& original, double tax, double discount)
{
discount = original * discount / 100;
tax = tax / 100;
double netPrice = original - discount + tax;
return netPrice;
}
int main()
{
double taxRate = 5.50; // = 5.50%
const double discount = 25;
double price;
double original;
void Receipt(const double& orig, const double& taxation,
const double& dis, const double& final);
GetOriginalPrice(original);
price = CalculateNetPrice(original, taxRate, discount);
Receipt(original, taxRate, discount, price);
cout << endl << "===============================================\n";
}
void Receipt(const double& original, const double& tax,
const double& discount, const double& finalPrice)
{
cout << "===============================================";
cout << "\nReceipt";
cout << "\n-----------------------------------------------";
cout << "\nOriginal Price: $" << original;
cout << "\nTax Rate: " << tax << "%";
cout << "\nDiscount Rate: " << discount << "%";
cout << "\nFinal Price: $" << finalPrice;
}
Here is an example of running the program:
Enter the original price of the item: $197.95 =============================================== Receipt ----------------------------------------------- Original Price: $197.95 Tax Rate: 5.5% Discount Rate: 25% Final Price: $148.517 =============================================== Press any key to close this window . . .
Practical Learning:Passing Arguments by Constant References
#include <iostream>
using namespace std;
// Rectangle
double MomentOfInertia(const double& b, const double& h)
{
return b * h * h * h / 3;
}
// Semi-Circle
double MomentOfInertia(const double& R)
{
const double PI = 3.14159;
return R * R * R * R * PI/ 8;
}
// Triangle
double MomentOfInertia(const double& b, const double& h, const int&)
{
return b * h * h * h / 12;
}
int main()
{
double length, height, radius;
void GetBaseAndHeight(double&, double&);
void GetRadius(double&);
cout << "Enter the dimensions of the rectangle\n";
GetBaseAndHeight(length, height);
cout << "Rectangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(length, height) << "mm\n\n";
cout << "Enter the radius of the semi-circle\n";
GetRadius(radius);
cout << "Semi-Circle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(radius) << "mm\n\n";
cout << "Enter the dimensions of the triangle\n";
GetBaseAndHeight(length, height);
cout << "\nTriangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << MomentOfInertia(length, height, 1) << "mm\n";
cout << "\n\n";
}
// Passing arguments by reference
void GetBaseAndHeight(double& B, double& H)
{
cout << "Enter Base: ";
cin >> B;
cout << "Enter Height: ";
cin >> H;
}
void GetRadius(double& R)
{
cout << "Enter Radius: ";
cin >> R;
}Enter the dimensions of the rectangle Enter Base: 18.85 Enter Height: 15.55 Rectangle Moment of inertia with regard to the X axis: I = 23625.5mm Enter the radius of the semi-circle Enter Radius: 14.25 Semi-Circle Moment of inertia with regard to the X axis: I = 16192.7mm Enter the dimensions of the triangle Enter Base: 8.95 Enter Height: 11.25 Triangle Moment of inertia with regard to the X axis: I = 1061.94mm
#include <iostream>
using namespace std;
// Rectangle
// This function receives one argument by reference and two arguments
// by constant references
void MomentOfInertia(double& moment,
const double& b, const double& h)
{
moment = b * h * h * h / 3;
}
// Semi-Circle
// This function receives one argument by reference and one by
// constant reference
void MomentOfInertia(double& moment, const double& R)
{
const double PI = 3.14159;
moment = R * R * R * R * PI/ 8;
}
// Triangle
// This function receives one argument by reference, two arguments by
// constant references and one argument by value
void MomentOfInertia(double& moment,
const double& b, const double& h, const int&)
{
moment = b * h * h * h / 12;
}
int main()
{
double length, height, radius, mRectangle, mSemiCircle, mTriangle;
void GetBaseAndHeight(double&, double&);
void GetRadius(double&);
cout << "Enter the dimensions of the rectangle\n";
GetBaseAndHeight(length, height);
MomentOfInertia(mRectangle, length, height);
cout << "Rectangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << mRectangle << "mm\n\n";
cout << "Enter the radius of the semi-circle\n";
GetRadius(radius);
MomentOfInertia(mSemiCircle, radius);
cout << "Semi-Circle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << mSemiCircle << "mm\n\n";
cout << "Enter the dimensions of the triangle\n";
GetBaseAndHeight(length, height);
MomentOfInertia(mRectangle, length, height, 1);
cout << "\nTriangle\n"
<< "Moment of inertia with regard to the X axis: ";
cout << "I = " << mRectangle << "mm\n";
cout << "\n\n";
}
// Passing arguments by reference
void GetBaseAndHeight(double& b, double& h)
{
cout << "Enter Base: ";
cin >> b;
cout << "Enter Height: ";
cin >> h;
}
void GetRadius(double& R)
{
cout << "Enter Radius: ";
cin >> R;
}Enter the dimensions of the rectangle Enter Base: 12.85 Enter Height: 8.85 Rectangle Moment of inertia with regard to the X axis: I = 2969.01mm Enter the radius of the semi-circle Enter Radius: 5.55 Semi-Circle Moment of inertia with regard to the X axis: I = 372.59mm Enter the dimensions of the triangle Enter Base: 10.75 Enter Height: 6.75 Triangle Moment of inertia with regard to the X axis: I = 275.511mm
|
|
|||
| Previous | Copyright © 1998-2026, FunctionX | Friday 03 October 2025, 08:15 | Next |
|
|
|||