Introduction to Functions
Introduction to Functions
Functions Fundamentals
Introduction to Functions
A function is a section of code that performs an action that other sections of a program can refer to. You create a function by writing code. The fundamental formula to create a function is:
options function-name(...)
{
}
Practical Learning: Introducing Functions
using static System.Console; int miles = 0; double pieceworkRate = 0.00; WriteLine("===================================="); WriteLine(" - Piece Work Delivery -"); WriteLine("===================================="); WriteLine("Miles Driven: {0}", miles); WriteLine("Piecework Rate: {0:n}", pieceworkRate); WriteLine("====================================");
============================================ - Piece Work Delivery - ============================================ Miles Driven: 0 Piecework Rate: 0.00 ============================================ Press any key to close this window . . .
The creation of a function starts with some options. As the simplest option you can apply, start a function with a keyword named void (that keyword is required for now).
The Name of a Function
A function must have a name. That name must follow some rules:
The Parentheses of a Function
The name of a function is followed by parentheses. At a minimum, the parentheses can be empty. Most of the time, you will write the parentheses on the same line as the name of the function. Otherwise, you can write each parenthesis on its own line. Here is an example:
void CarryMe ( )
Or like this:
void CarryMe( )
Or like this:
void CarryMe ( )
The Body of a Function
The body of a function follows the parentheses. After the parentheses, add the brackets: { and }. Here are examples:
void Send(){} void Publish(){ } void Salute( ){} void Continue( ){ } void Announce (){} void CarryMe ( ) { }
The section between the curly brackets is the body of the function. In that body, you can write the code that describes what the function is supposed to do.
Practical Learning: Creating Functions
using static System.Console; int miles = 0; double pieceworkRate = 0.00; // A function that requests a value void GetMiles() { Write("Miles Driven: "); miles = int.Parse(ReadLine()); } // Another function that requests a value void GetWorkRate() { Write("Piecework Rate: "); pieceworkRate = double.Parse(ReadLine()); } WriteLine("===================================="); WriteLine(" - Piece Work Delivery -"); WriteLine("===================================="); WriteLine("Miles Driven: {0}", miles); WriteLine("Piecework Rate: {0:n}", pieceworkRate); WriteLine("====================================");
Calling a Function
After creating a function, you can use it. Using a function is referred to as calling it. To call a simple function like the one we created above, type its name, followed by parentheses, and end it with a semicolon. This would be done as follows:
void Publish(){
}
Publish();
Practical Learning: Calling Functions
using static System.Console;
int miles = 0;
double pieceworkRate = 0.00;
// A function that requests a value
void GetMiles()
{
Write("Miles Driven: ");
miles = int.Parse(ReadLine());
}
// Another function that requests a value
void GetWorkRate()
{
Write("Piecework Rate: ");
pieceworkRate = double.Parse(ReadLine());
}
WriteLine("==============================================================");
WriteLine(" - Piece Work Delivery -");
WriteLine("==============================================================");
WriteLine("To evaluate the employee's pay, type the following information");
GetMiles();
GetWorkRate();
WriteLine("==============================================================");
WriteLine("Pay Summary");
WriteLine("--------------------------------------------------------------");
WriteLine("Miles Driven: {0}", miles);
WriteLine("Piecework Rate: {0:n}", pieceworkRate);
WriteLine("==============================================================");
============================================================== - Piece Work Delivery - ============================================================== To evaluate the employee's pay, type the following information Miles Driven: 1417 Piecework Rate: .47 ============================================================== Pay Summary -------------------------------------------------------------- Miles Driven: 1417 Piecework Rate: 0.47 ============================================================== Press any key to close this window . . .
Code Sections Delimiters
Microsoft Visual Studio provides various techniques to assist you with code writing and management. The characteristics include color-coded words, intuitive indentation, the IntelliSense, delimitation of sections of code, etc. Consider the following contents of the Code Editor based on what we have reviewed so far:
Notice that there are - buttons (dash buttons) on the left side of some lines of code. These allow you to collapse a section of code if you think you don't need to see it. To do this, you can click the - button (the dash button). If you click that - button, it changes into a + button (a plus button). Here is an example:
The + button allows you to expand a hidden code section. This behavior of creating + and - buttons is part of the Code Editor of Microsoft Visual Studio. To create these sections, the Code Editor follows some rules. For example, it looks for the start and end of such an item as a function.
Regions
Besides, or instead of, the sections of code created by the Code Editor, if you want, you can create your own sections. To create a section:
#region Whatever
and end it with
#endregion Whatever
When and where you start a region, the #region expression is required. On the right side of this expression, you can type anything you want on the line. To end the section, type #endregion, followed by anything you want. Consider the following example:
int someVariable; #region This section is reserved for quadrilateral shapes void ProcessRectangle() { } void ShowSquare() { } #endregion This is the end of the quadrilateral section string message;
You don't have to type anything on the right side of #endregion. After creating the region, the Code Editor would display a - button (dash) to the left side of #region with a line from there to the left of #endregion:
This then allows you to expand and collapse that section at will:
We mentioned that you didn't have to type anything on the right side of #endregion and you could leave it empty. In our example, notice that there is a rectangle with gray lines around the string that follows #region. This rectangle doesn't cover the string that follows #endregion. This means that if you don't type anything on the right side of #endregion, that section on the right side of the #region line would not show.
The Scope and Lifetime of a Variable
Introduction
The scope of a variable is the extent to which it is available to other members of a project. To manage this, a variable is said to have local or global scope.
Local Variables
A variable is said to be local if it is declared in the body of a function. Here is an example:
void Create()
{
string middleName;
}
When a variable is declared as local, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error.
A Global Variable
A variable is said to be global if it is declared (directly) in the Code Editor; that is, outside any curly brackets or outside any function. Here is an example:
string strDateOfBirth;
void Initialize()
{
}
void Present()
{
}
A variable that has been declared globally can be accessed by any code of the same document.
A Function that Returns a Value
Introduction
As seen in our introduction, a function has a body, which is delimited by curly brackets. Still, to indicate the end of execution of a function, type the return keyword followed by a semicolon. Here are examples:
void Communicate() { return; } void NeedToDiscuss() { return; } void TakeCare() { return; }
In this case, the return; statement doesn't serve any true purpose. It can be made useful when associated with a conditional statement.
Practical Learning: Introducing Value Returns
using static System.Console; double excess; double grossSalary; void CalculateTaxAmount() { /* https://tax.wv.gov/Documents/TaxForms/2020/it140.booklet.pdf * 1 - Single * 2 - Head of household * 3 - Married filing joint * 5 - Widow[er] with dependent child * Less than $10,000............3% of the taxable income * At least – But less than – * $ 10,000 $25,000 $300.00 plus 4% of excess over $10,000 * $ 25,000 $40,000 $900.00 plus 4.5% of excess over $25,000 * $ 40,000 $60,000 $1,575.00 plus 6% of excess over $40,000 * $ 60,000 $2,775.00 plus 6.5% of excess over $60,000 * */ double taxAmount = 0.00; if (grossSalary is < 10_000) { excess = grossSalary * 3.00 / 100; taxAmount = grossSalary * 3.00 / 100; } else if( (grossSalary is >= 10_000) && (grossSalary is < 25_000) ) { excess = ((grossSalary - 10_000) * 4.00 / 100); taxAmount = 300.00 + ((grossSalary - 10_000) * 4.00 / 100); } else if ((grossSalary is >= 25_000) && (grossSalary is < 40_000)) { excess = ((grossSalary - 10_000) * 4.00 / 100); taxAmount = 900 + ((grossSalary - 25_000) * 4.50 / 100); } else if ((grossSalary is >= 40_000) && (grossSalary is < 60_000)) { excess = ((grossSalary - 40_000) * 6.00 / 100); taxAmount = 1_575 + ((grossSalary - 40_000) * 6.00 / 100); } else // if (grossSalary is >= 60_000) { excess = ((grossSalary - 60_000) * 6.50 / 100); taxAmount = 2_775 + ((grossSalary - 60_000) * 6.50 / 100); } } void CalculateNetPay() { double pay = grossSalary; } WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine("Enter the information to prepare the taxes"); Write("Gross Salary: "); grossSalary = double.Parse(ReadLine()); double taxAmount = 0.00; double netPay = 0.00; WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine($"Gross Salary: {grossSalary:f}"); WriteLine("--------------------------------------------"); WriteLine($"Gross Salary: {excess:f}"); WriteLine($"Tax Amount: {taxAmount:f}"); WriteLine($"Net Pay: {netPay:f}"); WriteLine("============================================");
Returning From a Function
A function can be made to return a value. That is, if a function doesn't produce an explicit value, set its return type to void. If a function must produce a value, write the data type on the left side of the name of the function you are creating. Here is an example:
double Calculate()
{
}
Then, before the closing curly bracket of the function, type the return keyword, followed by what to return, followed by a semicolon.
Returning a Constant Value
The Primary way to return from a function is with a value. Here are examples:
int ProduceANumber() { return 2000; } int GetTriple() { return 3000; }
Returning a Variable
You can also return a variable. To do this, in the body of the function, declare a variable. If necessary, perform any operation you want. You can then assign a value or expression to the variable. Then, on the last line of the function, type return followed by the name of the variable. Here are examples:
int nbr; int GetNumber() { return nbr; } int GetTriple() { int result = Number * 3; return result; }
Practical Learning: Returning a Variable
using static System.Console; double grossSalary; double excess; // A function that returns a floating-point number double CalculateTaxAmount() { . . . double taxAmount = 0.00; if (grossSalary is < 10_000) { . . . } return taxAmount; } double CalculateNetPay() { double pay = grossSalary; return pay; } . . .
Returning an Expression
In an application, a variable is used if you are planning to use a value many times. If you need a value only once, you can use the value directly where it is needed. In the same way, if you need the returned value of a function only once, you can call the function directly where its value is needed.
Here is an example:
using static System.Console;
double grossSalary;
double EvaluateTaxLiability()
{
double first3000, next2000, next5000, over10000;
if (grossSalary is <= 3_000)
{
first3000 = 0.00;
next2000 = 0.00;
next5000 = 0.00;
over10000 = 0.00;
}
else if (grossSalary is <= 5_000)
{
first3000 = 0.00;
next2000 = (grossSalary - 3_000) * 3 / 100;
next5000 = 0.00;
over10000 = 0.00;
}
else if (grossSalary is <= 10_000)
{
first3000 = 0.00;
next2000 = 2_000 * 3 / 100;
next5000 = (grossSalary - 5_000) * 4 / 100;
over10000 = 0.00;
}
else // if (grossSalary is > 10_000)
{
first3000 = 0.00;
next2000 = 2_000 * 3 / 100;
next5000 = 5_000 * 4 / 100;
over10000 = (grossSalary - 10_000) * 5 / 100;
}
return first3000 + next2000 + next5000 + over10000;
}
A Simple Returning Function with no Body
Consider the following functions:
using static System.Console;
int nbr = 3_250;
int DoubleTheNumber()
{
return nbr * 2;
}
int GetTriple()
{
return nbr * 3;
}
double total = GetTriple();
WriteLine($"Number: {nbr}");
WriteLine($"Double: {Doubler}");
WriteLine($"Triple: {total}");
WriteLine("==============================================");
This would produce:
Number: 3250 Double: 6500 Triple: 9750 ============================================== Press any key to close this window . . .
If a function is small enough and it returns a value, remove the body of the curly brackets of the body of the function. After the parentheses of the function, type => followed by the returning expression and a semicolon. Here are examples:
using static System.Console; int nbr = 3_250; int DoubleTheNumber() => nbr * 2; int GetTriple() => nbr * 3; double total = GetTriple(); WriteLine($"Number: {nbr}"); WriteLine($"Double: {DoubleTheNumber}"); WriteLine($"Triple: {total}"); WriteLine("==============================================");
Calling a Function that Returns Something
Storing a Function Call in a Variable
If you have a function that produces a value and you use that value more than once, you can assign the function call to a variable and then use that variable as you see fit. Here are examples:
using static System.Console;
int ProduceANumber()
{
return 2000;
}
int GetTriple()
{
return 3000;
}
int value = 3250;
double total = GetTriple();
WriteLine($"Number: {ProduceANumber()}");
WriteLine($"Triple: {total}");
WriteLine("==============================================");
This would produce:
Number: 2000 Triple: 3000 ============================================== Press any key to close this window . . .
You can also use this technique if the function returns a variable. Here are examples:
using static System.Console; int nbr; int ProduceNumber() { return nbr; } int GetTriple() { int result = Number * 3; return result; } int value = 3250; nbr = value; double total = GetTriple(); WriteLine($"Number: {Number}"); WriteLine($"Triple: {total}"); WriteLine("==============================================");
This would produce:
Number: 3250 Triple: 9750 ============================================== Press any key to close this window . . .
Practical Learning: Calling a Function that Returns a Value
using static System.Console; double grossSalary; double excess; double CalculateTaxAmount() { /* https://tax.wv.gov/Documents/TaxForms/2020/it140.booklet.pdf * 1 - Single * 2 - Head of household * 3 - Married filing joint * 5 - Widow[er] with dependent child * Less than $10,000............3% of the taxable income * At least – But less than – * $ 10,000 $25,000 $300.00 plus 4% of excess over $10,000 * $ 25,000 $40,000 $900.00 plus 4.5% of excess over $25,000 * $ 40,000 $60,000 $1,575.00 plus 6% of excess over $40,000 * $ 60,000 $2,775.00 plus 6.5% of excess over $60,000 * */ double taxAmount = 0.00; if (grossSalary is < 10_000) { excess = grossSalary * 3.00 / 100; taxAmount = grossSalary * 3.00 / 100; } else if( (grossSalary is >= 10_000) && (grossSalary is < 25_000) ) { excess = ((grossSalary - 10_000) * 4.00 / 100); taxAmount = 300.00 + ((grossSalary - 10_000) * 4.00 / 100); } else if ((grossSalary is >= 25_000) && (grossSalary is < 40_000)) { excess = ((grossSalary - 10_000) * 4.00 / 100); taxAmount = 900 + ((grossSalary - 25_000) * 4.50 / 100); } else if ((grossSalary is >= 40_000) && (grossSalary is < 60_000)) { excess = ((grossSalary - 40_000) * 6.00 / 100); taxAmount = 1_575 + ((grossSalary - 40_000) * 6.00 / 100); } else // if (grossSalary is >= 60_000) { excess = ((grossSalary - 60_000) * 6.50 / 100); taxAmount = 2_775 + ((grossSalary - 60_000) * 6.50 / 100); } return taxAmount; } double CalculateNetPay() { double amount = CalculateTaxAmount(); double pay = grossSalary - amount; return pay; } WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine("Enter the information to prepare the taxes"); Write("Gross Salary: "); grossSalary = double.Parse(ReadLine()); double taxAmount = CalculateTaxAmount(); double netPay = CalculateNetPay(); WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine($"Gross Salary: {grossSalary:f}"); WriteLine("--------------------------------------------"); WriteLine($"Tax Amount: {taxAmount:f}"); WriteLine($"Excess: {excess:f}"); WriteLine($"Net Pay: {netPay:f}"); WriteLine("============================================");
============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Enter the information to prepare the taxes Gross Salary: 3748.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Gross Salary: 3748.85 -------------------------------------------- Tax Amount: 112.47 Excess: 112.47 Net Pay: 36361.38 ============================================ Press any key to close this window . . .
============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Enter the information to prepare the taxes Gross Salary: 18755.50 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Gross Salary: 18755.50 -------------------------------------------- Tax Amount: 650.22 Excess: 350.22 Net Pay: 18105.28 ============================================ Press any key to close this window . . .
Calling a Function Where it is Needed
Normally, when you call a function and assign the call to a variable, you are probably planning to use the returned value many times. If you are planning to use the returned value many times, you can call the function directly where its value is needed.
Practical Learning: Calling a function Where it is Needed
using static System.Console; double grossSalary; double excess; double CalculateTaxAmount() { . . . return taxAmount; } double CalculateNetPay() { return grossSalary - CalculateTaxAmount(); } WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine("Enter the information to prepare the taxes"); Write("Gross Salary: "); grossSalary = double.Parse(ReadLine()); WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine($"Gross Salary: {grossSalary:f}"); WriteLine("--------------------------------------------"); WriteLine($"Tax Amount: {CalculateTaxAmount():f}"); WriteLine($"Excess: {excess:f}"); WriteLine($"Net Pay: {CalculateNetPay():f}"); WriteLine("============================================");
============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Enter the information to prepare the taxes Gross Salary: 34848.35 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Gross Salary: 34848.35 -------------------------------------------- Tax Amount: 1343.18 Excess: 993.93 Net Pay: 33505.17 ============================================ Press any key to close this window . . .
using static System.Console;
double grossSalary;
double CalculateTaxAmount()
{
. . .
}
double CalculateNetPay() => grossSalary - CalculateTaxAmount();
. . .
============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Enter the information to prepare the taxes Gross Salary: 74682.75 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Gross Salary: 74682.75 -------------------------------------------- Tax Amount: 3729.38 Excess: 954.38 Net Pay: 70953.37 ============================================ Press any key to close this window . . .
Returning a Function Call
Imagine you have a function that returns a value. Imagine that you have to call that function in the body of another function to get the returned value of that function. Here are examples:
using static System.Console; int nbr; int MultiplyBy4() { return nbr * 4; } int Calculate() { int u = 38; int w = nbr * 3; return u + w; } int GetNumber() { int x = 428; nbr = x; int a = MultiplyBy4(); return a; } int Summarize() { int y = 3_258; nbr = y * 8; int q = Calculate(); return q; } nbr = 44; WriteLine($"Number: {Number}"); WriteLine($"Summary: {Summarize()}"); WriteLine("==============================================");
This would produce:
Number: 1712 Summary: 78230 ============================================== Press any key to close this window . . .
Notice that, in both cases, the property and the methods return a value produced by a function they are calling. In such a case, instead of storing the returned value of the function in a variable, you can call the function directly on the return line. Here are examples:
using static System.Console; int nbr; int MultiplyBy4() { return nbr * 4; } int Calculate() { int u = 38; int w = nbr * 3; return u + w; } int GetNumber() { int x = 428; nbr = x; return MultiplyBy4(); } int Summarize() { int y = 3_258; nbr = y * 8; return Calculate(); } nbr = 44; WriteLine($"Number: {Number}"); WriteLine($"Summary: {Summarize()}"); WriteLine("==============================================");
Ignoring the Returned Value af a Function
When a function is configured to return a value, when calling that function, we have seen that you can assign its call to a variable and use that variable as you see fit. Here is an example:
using static System.Console;
int zipCode, days;
int counterStart, counterEnd;
WriteLine("Electric Bill Evaluation");
WriteLine("======================================================");
IdentifyCustomer();
ReadCounter();
string strDisplayed = DisplayBill();
WriteLine(strDisplayed);
void IdentifyCustomer()
{
WriteLine("Enter the following pieces of information");
WriteLine("------------------------------------------------------");
Write("Customer ZIP Code: ");
zipCode = int.Parse(ReadLine());
}
void ReadCounter()
{
Write("Counter Start: ");
counterStart = int.Parse(ReadLine());
Write("Counter End: ");
counterEnd = int.Parse(ReadLine());
Write("Number of Days: ");
days = int.Parse(ReadLine());
WriteLine("======================================================");
}
string DisplayBill()
{
const double custChargeRate = 0.49315;
const double nrgChargeRate = 0.16580;
const double envChargeRate = 0.00043;
int electricUse = counterEnd - counterStart;
double custCharge = days * custChargeRate;
double energyCharge = electricUse * nrgChargeRate;
double envControlCharge = electricUse * envChargeRate;
double serviceTotal;
WriteLine("Electric Bill Summary:");
WriteLine("======================================================");
WriteLine("Counter Reading Start: {0, 8}", counterStart);
WriteLine("Counter Reading End: {0, 8}", counterEnd);
WriteLine("Total Electric Use: {0, 8}", electricUse);
WriteLine("Number of Days: {0, 8}", days);
WriteLine("------------------------------------------------------");
WriteLine("Energy Charge Credit");
WriteLine("------------------------------------------------------");
WriteLine("Customer Chargee: {0, 8:f}", custCharge);
WriteLine("Energy Charge: {0, 8:f}", energyCharge);
WriteLine("Environmental Control Charge: {0, 8:f}", envControlCharge);
WriteLine("------------------------------------------------------");
if ((zipCode == 20680) || (zipCode == 21737) || (zipCode == 21111))
{
serviceTotal = custCharge + energyCharge + envControlCharge - 3.15;
WriteLine("Low Income Assistance Fee: {0, 8:f}", 3.15);
}
else
serviceTotal = custCharge + energyCharge + envControlCharge;
WriteLine("Electric Servive Total: {0, 8:f}", serviceTotal);
WriteLine("======================================================");
return "The customer bill has been displayed";
}
Here is an example of running the application:
Electric Bill Evaluation ====================================================== Enter the following pieces of information ------------------------------------------------------ Customer ZIP Code: 20680 Counter Start: 10089 Counter End: 11126 Number of Days: 30 ====================================================== Electric Bill Summary: ====================================================== Counter Reading Start: 10089 Counter Reading End: 11126 Total Electric Use: 1037 Number of Days: 30 ------------------------------------------------------ Energy Charge Credit ------------------------------------------------------ Customer Chargee: 14.79 Energy Charge: 171.93 Environmental Control Charge: 0.45 ------------------------------------------------------ Low Income Assistance Fee: 3.15 Electric Servive Total: 184.03 ====================================================== The customer bill has been displayed Press any key to close this window . . .
Although a function may return a value, sometimes when calling such a function, you may not be interested in the returned value of that function. You have many options. As done above, you can declare a variable and assign the function call to it, but this is a waiste of resources because the compiler will have allocated memmory space for a variable you are not planning to use. As another option, in the placeholder of the variable and its data type, simply type an underscore. Here is an example:
using static System.Console;
int zipCode, days;
int counterStart, counterEnd;
WriteLine("Electric Bill Evaluation");
WriteLine("======================================================");
IdentifyCustomer();
ReadCounter();
_ = DisplayBill();
void IdentifyCustomer()
{
. . .
}
. . .
The last option is to simply call the function without assigning it to a variable or to an underscore placeholder. Here is an example:
using static System.Console;
int zipCode, days;
int counterStart, counterEnd;
WriteLine("Electric Bill Evaluation");
WriteLine("======================================================");
IdentifyCustomer();
ReadCounter();
DisplayBill();
void IdentifyCustomer()
{
. . .
}
. . .
Conditional Returns
Introduction
When performing its assignment, a function can encounter different situations. You can make the function produce a result that depends on some condition.
Conditionally Returning a Value
We are already familiar with the ability for a function to return a value. In some cases, the value you want to return is not a simple constant: It may depend on some condition. To make this happen, you have various options.
Practical Learning: Conditionally Returning a Value
using static System.Console; double grossSalary; double CalculateTaxAmount() { /* https://tax.wv.gov/Documents/TaxForms/2020/it140.booklet.pdf * 1 - Single * 2 - Head of household * 3 - Married filing joint * 5 - Widow[er] with dependent child * Less than $10,000............3% of the taxable income * At least – But less than – * $ 10,000 $25,000 $300.00 plus 4% of excess over $10,000 * $ 25,000 $40,000 $900.00 plus 4.5% of excess over $25,000 * $ 40,000 $60,000 $1,575.00 plus 6% of excess over $40,000 * $ 60,000 $2,775.00 plus 6.5% of excess over $60,000 * */ if (grossSalary is < 10_000) return grossSalary * 3.00 / 100; else if( (grossSalary is >= 10_000) && (grossSalary is < 25_000) ) return 300.00 + ((grossSalary - 10_000) * 4.00 / 100); else if ((grossSalary is >= 25_000) && (grossSalary is < 40_000)) return 900 + ((grossSalary - 25_000) * 4.50 / 100); else if ((grossSalary is >= 40_000) && (grossSalary is < 60_000)) return ((grossSalary - 40_000) * 6.00 / 100); else // if (grossSalary is >= 60_000) return 2_775 + ((grossSalary - 60_000) * 6.50 / 100); } double CalculateNetPay() => grossSalary - CalculateTaxAmount(); WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine("Enter the information to prepare the taxes"); Write("Gross Salary: "); grossSalary = double.Parse(ReadLine()); WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine($"Gross Salary: {grossSalary:f}"); WriteLine("--------------------------------------------"); WriteLine($"Tax Amount: {CalculateTaxAmount():f}"); WriteLine($"Net Pay: {CalculateNetPay():f}"); WriteLine("============================================");
============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Enter the information to prepare the taxes Gross Salary: 117635 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Gross Salary: 117635.00 -------------------------------------------- Tax Amount: 6521.27 Net Pay: 111113.73 ============================================ Press any key to close this window . . .
using static System.Console; double grossSalary; double CalculateTaxAmount() { /* https://tax.wv.gov/Documents/TaxForms/2020/it140.booklet.pdf * 1 - Single * 2 - Head of household * 3 - Married filing joint * 5 - Widow[er] with dependent child * Less than $10,000............3% of the taxable income * At least – But less than – * $ 10,000 $25,000 $300.00 plus 4% of excess over $10,000 * $ 25,000 $40,000 $900.00 plus 4.5% of excess over $25,000 * $ 40,000 $60,000 $1,575.00 plus 6% of excess over $40,000 * $ 60,000 $2,775.00 plus 6.5% of excess over $60,000 * */ if (grossSalary is < 10_000) return grossSalary * 3.00 / 100; else if ((grossSalary is >= 10_000) && (grossSalary is < 25_000)) return 300.00 + ((grossSalary - 10_000) * 4.00 / 100); else if ((grossSalary is >= 25_000) && (grossSalary is < 40_000)) return 900 + ((grossSalary - 25_000) * 4.50 / 100); else if ((grossSalary is >= 40_000) && (grossSalary is < 60_000)) return ((grossSalary - 40_000) * 6.00 / 100); else // if (grossSalary is >= 60_000) return 2_775 + ((grossSalary - 60_000) * 6.50 / 100); } double CalculateNetPay() => grossSalary - CalculateTaxAmount(); void Present() { WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); RequestSalary(); Display(); } Present(); void Display() { WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine($"Gross Salary: {grossSalary:f}"); WriteLine("--------------------------------------------"); WriteLine($"Tax Amount: {CalculateTaxAmount():f}"); WriteLine($"Net Pay: {CalculateNetPay():f}"); WriteLine("============================================"); } void RequestSalary() { WriteLine("Enter the information to prepare the taxes"); Write("Gross Salary: "); grossSalary = double.Parse(ReadLine()); }
============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Enter the information to prepare the taxes Gross Salary: 3884.68 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Gross Salary: 3884.68 -------------------------------------------- Tax Amount: 116.54 Net Pay: 3768.14 ============================================ Press any key to close this window . . .
Exiting Early From a Function
One of the goals of a condition statement is to check a condition in order to reach a conclusion. One of the goals of a function is to perform an action if a certain condition is met. In fact, by including a condition in a function, you can decide whether the action of a function is worth pursuing or completing. In the body of a function where you are checking a condition, once you find out that a certain condition is not met, you can stop checking the condition and get out of the function. This is done with the return keyword. To apply it, in the body of a conditional statement in a function, once you decide that the condition reaches the wrong outcome, type return and a semicolon.
Nesting a Function
Introduction
As mentioned in our introduction, a function is a section of code that solves a specific problem. Sometimes, you will find out that a function you had created is useful to only one other function. This means that, in this case, only a certain function calls a certain function and no other function calls that function B. If you have a section of code that only a certain function calls, you can create a function for that section in the body of the unique function that calls it.
A local function is a function that is created in the body of another function. A function created inside another function is also referred to as nested. The C# language provides various options to nest a function.
Nesting a Function in a Function
You primarily create a local function like any other, as long as you create it in the body of another function. After creating a nested function, call it by its name as we have done for the others.
Practical Learning: Nesting a Function
using static System.Console; double grossSalary; double CalculateTaxAmount() { /* https://tax.wv.gov/Documents/TaxForms/2020/it140.booklet.pdf * 1 - Single * 2 - Head of household * 3 - Married filing joint * 5 - Widow[er] with dependent child * Less than $10,000............3% of the taxable income * At least – But less than – * $ 10,000 $25,000 $300.00 plus 4% of excess over $10,000 * $ 25,000 $40,000 $900.00 plus 4.5% of excess over $25,000 * $ 40,000 $60,000 $1,575.00 plus 6% of excess over $40,000 * $ 60,000 $2,775.00 plus 6.5% of excess over $60,000 * */ if (grossSalary is < 10_000) return grossSalary * 3.00 / 100; else if ((grossSalary is >= 10_000) && (grossSalary is < 25_000)) return 300.00 + ((grossSalary - 10_000) * 4.00 / 100); else if ((grossSalary is >= 25_000) && (grossSalary is < 40_000)) return 900 + ((grossSalary - 25_000) * 4.50 / 100); else if ((grossSalary is >= 40_000) && (grossSalary is < 60_000)) return ((grossSalary - 40_000) * 6.00 / 100); else // if (grossSalary is >= 60_000) return 2_775 + ((grossSalary - 60_000) * 6.50 / 100); } double CalculateNetPay() => grossSalary - CalculateTaxAmount(); void Present() { WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); // Calling a nested function; the function is defined later RequestSalary(); // Nesting a function void Display() { WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine(" -=- West Virginia -=-"); WriteLine("============================================"); WriteLine($"Gross Salary: {grossSalary:f}"); WriteLine("--------------------------------------------"); WriteLine($"Tax Amount: {CalculateTaxAmount():f}"); WriteLine($"Net Pay: {CalculateNetPay():f}"); WriteLine("============================================"); } // Nesting another function void RequestSalary() { WriteLine("Enter the information to prepare the taxes"); Write("Gross Salary: "); grossSalary = double.Parse(ReadLine()); } // Calling another nested function Display(); } Present();
============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Enter the information to prepare the taxes Gross Salary: 4017.96 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- -=- West Virginia -=- ============================================ Gross Salary: 4017.96 -------------------------------------------- Tax Amount: 120.54 Net Pay: 3897.42 ============================================ Press any key to close this window . . .
|
|||
Previous | Copyright © 2001-2024, FunctionX | Monday 17 April 2023 | Next |
|