Introduction to Counting and Looping
Introduction to Counting and Looping
Fundamentals of Counting in Looping
Introduction
A loop is a statement that keeps checking a condition as being true and keeps executing a statement until the condition becomes false. In other words, a loop consists of performing a repeating action. The following three requirements should (must) be met. You must indicate:
Practical Learning: Introducing Looping
body { } .bold { font-weight: bold; } .text-right { text-align: right } .delimiter { margin: auto; width: 650px; } .top-bar { border-bottom: 6px solid blue; background-color: #f06d01 !important; } .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; } .navbar-light .navbar-brand { color: white; } .navbar-light .navbar-brand:hover { color: yellow; } .navbar-light .navbar-brand:focus { color: khaki; } .navbar-light .navbar-brand { font-family: Georgia, Garamond, 'Times New Roman', serif; } .nav-link { font-family: Georgia, Garamond, 'Times New Roman', serif; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - Business Depreciations</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/BusinessDepreciations.css" asp-append-version="true" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 top-bar"> <div class="container"> <a class="navbar-brand" asp-area="" asp-page="/Index">Business Depreciations</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-white" asp-area="" asp-page="/StraightLineMethod">Straight-Line Method</a> </li> <li class="nav-item"> <a class="nav-link text-white" asp-area="" asp-page="/DoubleDecliningBalance">Double-Declining Balance</a> </li> <li class="nav-item"> <a class="nav-link text-white" asp-area="" asp-page="/SumYearsDigits">Sum of Year's Digits</a> </li> </ul> </div> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> <p class="text-center common-font">© 2022 - Business Depreciations - <a asp-area="" asp-page="/Privacy">Privacy</a></p> </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
@page @model BusinessDepreciations1.Pages.StraightLineMethodModel @using static System.Console @{ int estimatedLife = 0; double salvageValue = 0.00; string? strDepreciationRate = null; double machineCost = 0.00, yearlyDepreciation = 0.00; string? strDepreciableAmount = null, strYearlyDepreciation = null; if (Request.HasFormContentType) { try { machineCost = double.Parse(Request.Form["txtMachineCost"]); } catch (FormatException) { WriteLine("You must have typed a valid value that represents the " + "cost of the machine. Since you did not provide a " + "valid value, we will set the machine cost to 0.00."); } try { salvageValue = double.Parse(Request.Form["txtSalvageValue"]); } catch (FormatException) { WriteLine("You must have provided that value you estimate the machine " + "will have at the end of the cycle (or the end of its " + "life). Since you didn't enter a valid value, we will " + "consider the estimated end value to 0.00."); } try { estimatedLife = int.Parse(Request.Form["txtEstimatedLife"]); } catch (FormatException) { WriteLine("You didn't enter a valid number of years for the life of " + "the machine. Instead, we will consider that this machine " + "has no life, or a life of 0 years."); } if (estimatedLife == 0) throw new DivideByZeroException("The value for the length of the estimated life of the machine must always be greater than 0."); double depreciatiableAmount = machineCost - salvageValue; double depreciationRate = 100 / estimatedLife; yearlyDepreciation = depreciatiableAmount / estimatedLife; strDepreciableAmount = $"{(depreciatiableAmount):n}"; strDepreciationRate = $"{(depreciationRate):n}"; strYearlyDepreciation = $"{yearlyDepreciation:f}"; WriteLine("===================================="); WriteLine("Depreciation - Straight-Line Method"); WriteLine("------------------------------------"); WriteLine("Machine Cost: {0}", machineCost); WriteLine("Salvage Value: {0}", salvageValue); WriteLine("Estimate Life: {0} Years", estimatedLife); WriteLine("Depreciation Rate: {0}%", depreciationRate); WriteLine("------------------------------------"); WriteLine("Depreciable Amount: {0}", depreciatiableAmount); WriteLine("Yearly Depreciation: {0}", yearlyDepreciation); WriteLine("===================================="); } } <h1 class="common-font bold text-center">Machine Depreciation - Straight-Line Method</h1> <hr /> <form name="PayrollEvaluation" method="post" class="common-font"> <table align="center" style="width: 325px" class="table"> <tr> <td style="width: 150px" class="bold">Machine Cost:</td> <td><input type="text" style="" id="txtMachineCost" name="txtMachineCost" value="@machineCost" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Salvage Value:</td> <td><input type="text" id="txtSalvageValue" name="txtSalvageValue" value="@salvageValue" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Estimated Life:</td> <td><input type="text" id="txtEstimatedLife" name="txtEstimatedLife" value="@estimatedLife" class="form-control text-based" /></td> <td>years</td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Calculate Depreciation" name="btnCalculate" style="width: 200px" /></td> </tr> </table> <hr /> <table style="width: 325px" align="center" class="common-font table"> <tr> <td class="bold">Machine Cost:</td> <td>@machineCost</td> </tr> <tr> <td class="bold">Salvage Value:</td> <td>@salvageValue</td> </tr> <tr> <td class="bold">Estimate Life:</td> <td>@estimatedLife Years</td> </tr> <tr> <td class="bold">Depreciation Rate:</td> <td>@strDepreciationRate %</td> </tr> <tr> <td class="bold">Depreciable Amount:</td> <td>@strDepreciableAmount</td> </tr> <tr> <td class="bold">Yearly Depreciation:</td> <td>@strYearlyDepreciation /month</td> </tr> </table> </form>
while a Condition is True
One of the techniques used to use a loop is to first perform an operation, then check a condition to repeat a statement. To support this, the C-based languages, including C#, provide an operator named while. The formula to use it is:
while(condition) statement;
If you are using Microsoft Visual Studio, to create a while loop, right-click the section where you want to add it and click Insert Snippet... Double-click Visual C#. In the list, double-click while.
To perform a while loop, the compiler first examines the condition. If the condition is true, then it executes the statement. After executing the statement, the condition is checked again. As long as the condition is true, the compiler will keep executing the statement. When or once the condition becomes false, the compiler exits the loop.
Most of the time, the statement goes along with a way to move forward or backwards. As a result, the section that has the statement is usually delimited by curly brackets that show the body of the while condition. As a result, the formula for the while condition becomes:
while(condition) { . . . statement . . . };
The while loop can be illustrated as follows:
Most of the time, before entering in a while loop, you should have an object or a variable that has been initialized or the variable provides a starting value. From there, you can ask the compiler to check another condition and keep doing something as long as that condition is true. Here is an example:
@page @model Exercise.Pages.ExerciseModel @using static System.Console @{ // Consider a starting value as 0 int number = 0; // Start the loop while(number <= 5) { // As long as the above value is lower than 5, ... // ... display that number WriteLine("Make sure you review the time sheet before submitting it."); // Increase the number (or counter) number++; // Check the number (or counter again. Is it still less than 4? } }
This would produce:
Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it.
The while loop is used to first check a condition and then execute a statement. If the condition is false, the statement would never execute. Consider the following code:
@page @model Exercise.Pages.ExerciseModel @using static System.Console @{ int number = 5; while(number <= 4) { WriteLine("Make sure you review the time sheet before submitting it."); number++; } }
When this code executes, nothing from the while loop would execute because, as the condition is checked in the beginning, it is false and the compiler would not get to the statement.
Introduction to Loops and Lists
As you may know already, a list is a group of items. Here is an example:
@{
double number1 = 12.44;
double number2 = 525.38;
double number3 = 6.28;
double number4 = 2448.32;
double number5 = 632.04;
}
The items are grouped from a starting to an ending points. The list can created as an array. Here is an example:
@{
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
The list has a number of items. We saw that you can specify the number of items when creating the array. Here is an example:
@{
double[] numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
Or, to get the number of items of an array, the array variable is equipped with a property named Length that it gets from the Array class. Here is an example of accessing it:
@page @model Exercise.Pages.ExerciseModel @using static System.Console @{ double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; WriteLine("Number of Items in the array: {0}", numbers.Length); WriteLine("================================="); }
This would produce:
Number of Items in the array: 5 =================================
Each item can be located by its index from 0 to Number of Items - 1. Here is an example that accesses each of the items:
@page @model Exercise.Pages.ExerciseModel @using static System.Console @{ double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; WriteLine("Number: {0}", numbers[0]); WriteLine("Number: {0}", numbers[1]); WriteLine("Number: {0}", numbers[2]); WriteLine("Number: {0}", numbers[3]); WriteLine("Number: {0}", numbers[4]); WriteLine("============================"); }
This would produce:
Number: 12.44 Number: 525.38 Number: 6.28 Number: 2448.32 Number: 632.04 ============================
As opposed to accessing one item at a time, a loop allows you to access the items as a group. Each item can still be accessed by its index. You can first declare a variable that would hold the index for an item. Here is an example:
@{
int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
To access an item in a loop, use the name of the array but pass the index in the square brackets of the variable. Here is an example:
@page @model Exercise.Pages.ExerciseModel @using static System.Console @{ int counter = 0; double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; while (counter <= 4) { WriteLine("Number: {0}", numbers[counter]); counter++; } WriteLine("================================="); }
In the same way, to change the value of an item, access it by its index and assign the desired value to it. Here is an example:
@page
@model Exercise.Pages.ExerciseModel
@using static System.Console
@{
int counter = 0;
Random rndNumber = new Random();
int[] numbers = new int[] { 203, 81, 7495, 40, 9580 };
WriteLine("====================================");
WriteLine("Original List");
while (counter <= 4)
{
WriteLine("Number: {0}", numbers[counter]);
counter++;
}
WriteLine("-------------------------------------");
WriteLine("Updating the numbers of the list...");
counter = 0;
while (counter <= 4)
{
numbers[counter] = rndNumber.Next(1001, 9999);
counter++;
}
WriteLine("-------------------------------------");
counter = 0;
WriteLine("Updated Numbers");
while (counter <= 4)
{
WriteLine("Number: {0}", numbers[counter]);
counter++;
}
WriteLine("====================================");
}
This would produde:
==================================== Original List Number: 203 Number: 81 Number: 7495 Number: 40 Number: 9580 ------------------------------------- Updating the numbers of the list... ------------------------------------- Updated Numbers Number: 9822 Number: 6086 Number: 8411 Number: 5176 Number: 4202 ====================================
Practical Learning: Introducing Loops in an Array
@page @model BusinessDepreciations1.Pages.StraightLineMethodModel @using static System.Console @{ int year = 1; int counter = 1; int estimatedLife = 0; double salvageValue = 0.00; string? strDepreciationRate = null; double[] bookValues = new double[10]; double machineCost = 0.00, yearlyDepreciation = 0.00; string? strDepreciableAmount = null, strYearlyDepreciation = null; if (Request.HasFormContentType) { try { machineCost = double.Parse(Request.Form["txtMachineCost"]); } catch (FormatException) { WriteLine("You must have typed a valid value that represents the " + "cost of the machine. Since you did not provide a " + "valid value, we will set the machine cost to 0.00."); } try { salvageValue = double.Parse(Request.Form["txtSalvageValue"]); } catch (FormatException) { WriteLine("You must have provided that value you estimate the machine " + "will have at the end of the cycle (or the end of its " + "life). Since you didn't enter a valid value, we will " + "consider the estimated end value to 0.00."); } try { estimatedLife = int.Parse(Request.Form["txtEstimatedLife"]); } catch (FormatException) { WriteLine("You didn't enter a valid number of years for the life of " + "the machine. Instead, we will consider that this machine " + "has no life, or a life of 0 years."); } if (estimatedLife == 0) throw new DivideByZeroException("The value for the length of the estimated life of the machine must always be greater than 0."); double depreciatiableAmount = machineCost - salvageValue; double depreciationRate = 100 / estimatedLife; yearlyDepreciation = depreciatiableAmount / estimatedLife; strDepreciableAmount = $"{(depreciatiableAmount):n}"; strDepreciationRate = $"{(depreciationRate):n}"; strYearlyDepreciation = $"{yearlyDepreciation:f}"; WriteLine("===================================="); WriteLine("Depreciation - Straight-Line Method"); WriteLine("------------------------------------"); WriteLine("Machine Cost: {0}", machineCost); WriteLine("Salvage Value: {0}", salvageValue); WriteLine("Estimate Life: {0} Years", estimatedLife); WriteLine("Depreciation Rate: {0}%", depreciationRate); WriteLine("------------------------------------"); WriteLine("Depreciable Amount: {0}", depreciatiableAmount); WriteLine("Yearly Depreciation: {0}", yearlyDepreciation); WriteLine("===================================="); bookValues = new double[estimatedLife + 1]; bookValues[0] = machineCost; while (counter <= @estimatedLife - 1) { bookValues[counter] = bookValues[counter - 1] - yearlyDepreciation; counter++; } counter = 0; bookValues[estimatedLife] = salvageValue; WriteLine(" Accumulated"); WriteLine("Year Book Value Distribution"); while (counter <= estimatedLife - 1) { double accumulatedDepreciation = yearlyDepreciation * year; WriteLine("------------------------------------"); WriteLine(" {0} {1, 10} {2, 12}", year, bookValues[counter], accumulatedDepreciation); year++; counter++; } WriteLine("===================================="); } } <h1 class="common-font text-center">Machine Depreciation Evaluation - Straight-Line Method</h1> <hr /> <form name="PayrollEvaluation" method="post" class="common-font"> <table align="center" style="width: 325px" class="table"> <tr> <td style="width: 150px" class="bold">Machine Cost:</td> <td><input type="text" style="" id="txtMachineCost" name="txtMachineCost" value="@machineCost" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Salvage Value:</td> <td><input type="text" id="txtSalvageValue" name="txtSalvageValue" value="@salvageValue" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Estimated Life:</td> <td><input type="text" id="txtEstimatedLife" name="txtEstimatedLife" value="@estimatedLife" class="form-control text-based" /></td> <td>years</td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Calculate Depreciation" name="btnCalculate" style="width: 200px" /></td> </tr> </table> <hr /> <table style="width: 325px" align="center" class="common-font table"> <tr> <td class="bold">Machine Cost:</td> <td>@machineCost</td> </tr> <tr> <td class="bold">Salvage Value:</td> <td>@salvageValue</td> </tr> <tr> <td class="bold">Estimate Life:</td> <td>@estimatedLife Years</td> </tr> <tr> <td class="bold">Depreciation Rate:</td> <td>@strDepreciationRate %</td> </tr> <tr> <td class="bold">Depreciable Amount:</td> <td>@strDepreciableAmount</td> </tr> <tr> <td class="bold">Yearly Depreciation:</td> <td>@strYearlyDepreciation /month</td> </tr> </table> <hr /> @{ year = 1; counter = 1; bookValues = new double[estimatedLife + 1]; bookValues[0] = machineCost; while (counter <= @estimatedLife - 1) { bookValues[counter] = bookValues[counter - 1] - yearlyDepreciation; counter++; } counter = 0; bookValues[estimatedLife] = salvageValue; } <table style="width: 500px" align="center" class="common-font table"> <tr> <td class="bold text-center">Year</td> <td class="bold text-center">Book Value</td> <td class="bold text-center">Accumulated Distribution</td> </tr> @while (counter <= @estimatedLife - 1) { string strBookValues = $"{bookValues[counter]:F}"; string strAccumulatedDepreciation = $"{(yearlyDepreciation * year):F}"; <tr> <td class="text-center">@year</td> <td class="text-center">@strBookValues</td> <td class="text-center">@strAccumulatedDepreciation</td> </tr> year++; counter++; } </table> </form>
Doing Something While a Condition is True
Sometimes, before executing a repeating action, or before checking the condition for the first time, you may want to first execute a statement. In other words, you want to first execute a statement before checking its condition. To make this possible, the C-based languages, which includes C#, use a combination of the do and the while keywords used in a formula as follows:
do statement while (condition);
If the statement includes more than one line of code, you must include the statement section in a body included inside curly brackets. The formula becomes:
do { statement } while (condition);
The body delimited by curly brackets can be used even it there is only one statement to exercute.
The do...while condition executes a statement first. After the first execution of the statement, the compiler examines the condition. If the condition is true, then it executes the statement again. It will keep executing the statement as long as the condition is true. Once the condition becomes false, the looping (the execution of the statement) will stop. This can be illustrated as follows:
If the statement is a short one, such as made of one line, you can write it after the do keyword. Like the if and the while statements, the condition being checked must be included between parentheses. The whole do...while statement must end with a semicolon. Here is an example:
If you are creating the condition in a method of a class, if the statement is long and should span more than one line, start it with an opening curly bracket "{" and end it with a closing curly bracket "}".
@page @model Exercise.Pages.ExerciseModel @using static System.Console @{ int number = 0; do { WriteLine("Make sure you review the time sheet before submitting it."); number++; } while (number <= 4); WriteLine("=========================================================="); };
This would produce:
Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. ==========================================================
Introduction
Some operations require that you visit each item in a range, usually a range of numbers. To let you do this,the C-based languages, including C#, provide the for keyword. The primary formula to follow is:
for(start; end; frequency) statement;
The for loop is typically used to visit each number of a range. For this reason, it is divided in three parts. The first section specifies the starting point of the range. This start expression can be a variable assigned to the starting value. An example would be int count = 0;.
The second section sets the counting limit. This end expression is created as a Boolean expression that can be true or false. An example would be count < 5. This means that the counting would continue as long as the value of start is less than 5. When such a condition becomes false, the loop or counting would stop.
The last section determines how the counting should move from one value to another. If you want the loop to increment the value from start, you can apply the ++ operator to it. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@{
for (int number = 0; number <= 5; number++)
WriteLine("The time sheet was checked and this payroll has been approved.");
WriteLine("===============================================================");
}
This would produce:
The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. ===============================================================
In the above example, we declared the variable in the for expression. You can use a variable from any source or declare a variable before the loop. Here is an example:
@using static System.Console @{ int number; for (number = 0; number <= 5; number++) WriteLine("The time sheet was checked and this payroll has been approved."); WriteLine("==============================================================="); }
In the above code, we first declared a variable, then initialized it in the loop. If you have a variable that has been initialize and want to use it in the loop, in the section of the loop where the variable is supposed to be initialized, leave it empty. Here is an example:
@using static System.Console
@{
span class="codered">int number = 0;
for(; number <= 5; number++)
WriteLine("The time sheet was checked and this payroll has been approved.");
WriteLine("===============================================================");
}
Practical Learning: Counting for a Loop (and doing Something)
@page @model BusinessDepreciations1.Pages.DoubleDecliningBalanceModel @using static System.Math @using static System.Console @{ int year = 1; int counter = 1; int estimatedLife = 1; double decliningRate = 0.00; double machineCost = 0.00; double depreciationAmount = 0.00; string? strDecliningRate = null; string? strDepreciationFirstYear = null; double[] yearlyDepreciations = new double[estimatedLife]; double[] bookValuesEndOfYear = new double[estimatedLife]; double[] bookValuesBeginningOfYear = new double[estimatedLife]; if (Request.HasFormContentType) { try { machineCost = double.Parse(Request.Form["txtMachineCost"]); } catch (FormatException) { WriteLine("You must have typed a valid value that represents the " + "cost of the machine. Since you did not provide a " + "valid value, we will set the machine cost to 0.00."); } try { estimatedLife = int.Parse(Request.Form["txtEstimatedLife"]); } catch (FormatException) { WriteLine("You didn't enter a valid number of years for the life of " + "the machine. Instead, we will consider that this machine " + "has no life, or a life of 0 years."); } if (estimatedLife == 0) throw new DivideByZeroException("The value for the length of the estimated life of the machine must always be greater than 0."); decliningRate = (100.00 / estimatedLife) * 2.00; depreciationAmount = machineCost * decliningRate / 100.00; strDecliningRate = $"{(decliningRate):n}"; strDepreciationFirstYear = $"{(depreciationAmount):n}"; WriteLine(" =-= Depreciation - Double Declining Balance =-="); WriteLine("==========================================================="); WriteLine("Depreciation Estimation"); WriteLine("-----------------------------------------------------------"); WriteLine("Machine Cost: {0:N}", machineCost); WriteLine("-----------------------------------------------------------"); WriteLine("Estimated Life: {0} years", estimatedLife); WriteLine("-----------------------------------------------------------"); WriteLine("Declining Rate: {0:N}", decliningRate); WriteLine("-----------------------------------------------------------"); WriteLine("Depreciation First Year: {0:N}", depreciationAmount); WriteLine("==========================================================="); yearlyDepreciations = new double[estimatedLife]; bookValuesEndOfYear = new double[estimatedLife]; bookValuesBeginningOfYear = new double[estimatedLife]; // Year 1 bookValuesBeginningOfYear[0] = machineCost; yearlyDepreciations[0] = machineCost * decliningRate / 100.00; bookValuesEndOfYear[0] = machineCost - yearlyDepreciations[0]; // The other years do { yearlyDepreciations[counter] = bookValuesEndOfYear[counter - 1] * decliningRate / 100.00; bookValuesEndOfYear[counter] = bookValuesEndOfYear[counter - 1] - yearlyDepreciations[counter]; bookValuesBeginningOfYear[counter] = bookValuesEndOfYear[counter - 1]; counter++; } while (counter <= estimatedLife - 1); counter = 0; Console.WriteLine(" Book Value at Book Value at"); Console.WriteLine("Beginning of Year Depreciation for Year End of Year"); Console.WriteLine("-----------------------------------------------------------"); do { Console.WriteLine("{0,10}{1,22}{2,20}", year, Ceiling(@bookValuesBeginningOfYear[counter]), Ceiling(@yearlyDepreciations[counter]), Ceiling(@bookValuesEndOfYear[counter])); Console.WriteLine("-----------------------------------------------------------"); year++; counter++; } while (counter <= estimatedLife - 1); } } <h1 class="common-font text-center bold">Machine Depreciation - Double-Declining Balance</h1> <hr /> <form name="PayrollEvaluation" method="post" class="common-font"> <table align="center" style="width: 325px" class="table"> <tr> <td style="width: 150px" class="bold">Machine Cost:</td> <td><input type="text" style="" id="txtMachineCost" name="txtMachineCost" value="@machineCost" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Estimated Life:</td> <td><input type="text" id="txtEstimatedLife" name="txtEstimatedLife" value="@estimatedLife" class="form-control text-based" /></td> <td>years</td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Calculate Depreciation" name="btnCalculate" style="width: 200px" /></td> </tr> </table> <hr /> <table style="width: 325px" align="center" class="common-font table"> <tr> <td class="bold">Machine Cost:</td> <td>@machineCost</td> </tr> <tr> <td class="bold">Estimate Life:</td> <td>@estimatedLife Years</td> </tr> <tr> <td class="bold">Declining Rate:</td> <td>@strDecliningRate %</td> </tr> <tr> <td class="bold">Depreciation First Year:</td> <td>@strDepreciationFirstYear</td> </tr> </table> <hr /> @{ yearlyDepreciations = new double[estimatedLife]; bookValuesEndOfYear = new double[estimatedLife]; bookValuesBeginningOfYear = new double[estimatedLife]; // Year 1 bookValuesBeginningOfYear[0] = machineCost; yearlyDepreciations[0] = machineCost * decliningRate / 100.00; bookValuesEndOfYear[0] = machineCost - yearlyDepreciations[0]; year = 1; counter = 1; // The other years for(counter = 1; counter <= estimatedLife - 1; counter++) { yearlyDepreciations[counter] = bookValuesEndOfYear[counter - 1] * decliningRate / 100.00; bookValuesEndOfYear[counter] = bookValuesEndOfYear[counter - 1] - yearlyDepreciations[counter]; bookValuesBeginningOfYear[counter] = bookValuesEndOfYear[counter - 1]; } counter = 0; <table style="width: 550px" align="center" class="common-font table"> <tr> <td> </td> <td class="bold text-center">Book Value at</td> <td> </td> <td class="bold text-center">Book Value at</td> </tr> <tr> <td class="bold text-center">Year</td> <td class="bold text-center">Beginning of Year</td> <td class="bold text-center">Depreciation for Year</td> <td class="bold text-center">End of Year</td> </tr> @do { <tr> <td class="text-center">@year</td> <td class="text-center">@System.Math.Ceiling(@bookValuesBeginningOfYear[counter])</td> <td class="text-center">@System.Math.Ceiling(@yearlyDepreciations[counter])</td> <td class="text-center">@System.Math.Ceiling(@bookValuesEndOfYear[counter])</td> </tr> year++; counter++; } while (counter <= @estimatedLife - 1); </table> } </form>
@page @model BusinessDepreciations1.Pages.SumYearsDigitsModel @using static System.Math @using static System.Console @{ int year = 0; int counter = 0; int sumOfYears = 0; int estimatedLife = 0; double machineCost = 0.00; double salvageValue = 0.00; double depreciatiableAmount = 0.00; double[] depreciations = new double[0]; string[] fractions = new string[0]; string? strDepreciableAmount = null; if (Request.HasFormContentType) { try { machineCost = double.Parse(Request.Form["txtMachineCost"]); } catch (FormatException) { WriteLine("You must have typed a valid value that represents the " + "cost of the machine. Since you did not provide a " + "valid value, we will set the machine cost to 0.00."); } try { salvageValue = double.Parse(Request.Form["txtSalvageValue"]); } catch (FormatException) { WriteLine("You must have provided that value you estimate the machine " + "will have at the end of the cycle (or the end of its " + "life). Since you didn't enter a valid value, we will " + "consider the estimated end value to 0.00."); } try { estimatedLife = int.Parse(Request.Form["txtEstimatedLife"]); } catch (FormatException) { WriteLine("You didn't enter a valid number of years for the life of " + "the machine. Instead, we will consider that this machine " + "has no life, or a life of 0 years."); } if (estimatedLife == 0) throw new DivideByZeroException("The value for the length of the estimated life of the machine must always be greater than 0."); depreciatiableAmount = machineCost - salvageValue; strDepreciableAmount = $"{depreciatiableAmount:n}"; WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-="); WriteLine("==============================================="); WriteLine("Depreciation Estimation"); WriteLine("-----------------------------------------------"); WriteLine("Machine Cost: {0:N}", machineCost); WriteLine("Salvage Value: {0:N}", salvageValue); WriteLine("Estimated Life: {0}", estimatedLife); WriteLine("-----------------------------------------------"); WriteLine("depreciatiable Amount: {0:N}", depreciatiableAmount); year = 1; depreciations = new double[estimatedLife]; fractions = new string[estimatedLife]; sumOfYears = (estimatedLife * (estimatedLife + 1)) / 2; for (int i = 0; i <= estimatedLife - 1; i++) { fractions[counter] = (i + 1) + "/" + sumOfYears; depreciations[counter] = (depreciatiableAmount * (i + 1)) / sumOfYears; counter++; } WriteLine("==============================================="); WriteLine("Year Fraction Depreciation"); WriteLine("-----------------------------------------------"); for (int i = 0; i <= @estimatedLife - 1; i++) { WriteLine("{0,3}{1,15}{2,20}", year, fractions[i], Ceiling(@depreciations[i])); WriteLine("-----------------------------------------------"); year++; } WriteLine("==============================================="); } } <h1 class="bold common-font text-center">Machine Depreciation - Straight-Line Method</h1> <hr /> <form name="PayrollEvaluation" method="post" class="common-font"> <table align="center" style="width: 350px" class="table"> <tr> <td style="width: 150px" class="bold">Machine Cost:</td> <td><input type="text" style="" id="txtMachineCost" name="txtMachineCost" value="@machineCost" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Salvage Value:</td> <td><input type="text" id="txtSalvageValue" name="txtSalvageValue" value="@salvageValue" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Estimated Life:</td> <td><input type="text" id="txtEstimatedLife" name="txtEstimatedLife" value="@estimatedLife" class="form-control text-based" /></td> <td>years</td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Calculate Depreciation" name="btnCalculate" style="width: 200px" /></td> </tr> </table> <hr /> <table style="width: 350px" align="center" class="common-font table"> <tr> <td class="bold">Depreciable Amount:</td> <td>@strDepreciableAmount</td> </tr> </table> <hr /> @{ year = 1; counter = 0; depreciations = new double[estimatedLife]; fractions = new string[estimatedLife]; sumOfYears = (estimatedLife * (estimatedLife + 1)) / 2; for(int i = 0; i <= estimatedLife - 1; i++) { fractions[counter] = (i + 1) + "/" + sumOfYears; depreciations[counter] = (depreciatiableAmount * (i + 1)) / sumOfYears; counter++; } } <table style="width: 525px" align="center" class="common-font table"> <tr> <td class="bold text-center">Year</td> <td class="bold text-center">Fraction</td> <td class="bold text-center">Depreciation</td> </tr> @for(int i = 0; i <= @estimatedLife - 1; i++) { <tr> <td class="text-center">@year</td> <td class="text-center">@fractions[i]</td> <td class="text-center">@Ceiling(@depreciations[i])</td> </tr> year++; } </table> </form>
Reversing the Counting Direction
Instead of proceeding from a lower to a higher value in a loop, you can visit the values from the end of a list to the beginning. To do this, fir the first part of the loop, set the last value as the starting point. For the second part of the loop, specify the possible ending point as the first value. For its Boolean expression, you usually set a condition that would work backwards. This is usually done using the > or the >= operator. The last section usually applies the -- operator to the variable of the loop. The formula to follow can be the following:
for(end; start; frequency) statement;
Practical Learning: Reversing the Counting Direction
@page @model BusinessDepreciations1.Pages.SumYearsDigitsModel @using static System.Math @using static System.Console @{ int year = 0; int reverse = 0; int sumOfYears = 0; int estimatedLife = 0; double machineCost = 0.00; double salvageValue = 0.00; double depreciatiableAmount = 0.00; double[] depreciations = new[0]; string[] fractions = new[0]; string? strDepreciableAmount = null; if (Request.HasFormContentType) { try { machineCost = double.Parse(Request.Form["txtMachineCost"]); } catch (FormatException) { WriteLine("You must have typed a valid value that represents the " + "cost of the machine. Since you did not provide a " + "valid value, we will set the machine cost to 0.00."); } try { salvageValue = double.Parse(Request.Form["txtSalvageValue"]); } catch (FormatException) { WriteLine("You must have provided that value you estimate the machine " + "will have at the end of the cycle (or the end of its " + "life). Since you didn't enter a valid value, we will " + "consider the estimated end value to 0.00."); } try { estimatedLife = int.Parse(Request.Form["txtEstimatedLife"]); } catch (FormatException) { WriteLine("You didn't enter a valid number of years for the life of " + "the machine. Instead, we will consider that this machine " + "has no life, or a life of 0 years."); } if (estimatedLife == 0) throw new DivideByZeroException("The value for the length of the estimated life of the machine must always be greater than 0."); depreciatiableAmount = machineCost - salvageValue; strDepreciableAmount = $"{depreciatiableAmount:n}"; WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-="); WriteLine("==============================================="); WriteLine("Depreciation Estimation"); WriteLine("-----------------------------------------------"); WriteLine("Machine Cost: {0:N}", machineCost); WriteLine("Salvage Value: {0:N}", salvageValue); WriteLine("Estimated Life: {0}", estimatedLife); WriteLine("-----------------------------------------------"); WriteLine("depreciatiable Amount: {0:N}", depreciatiableAmount); year = 1; depreciations = new double[estimatedLife]; fractions = new string[estimatedLife]; sumOfYears = (estimatedLife * (estimatedLife + 1)) / 2; for (int i = estimatedLife - 1; i >= 0; i--) { fractions[reverse] = (i + 1) + "/" + sumOfYears; depreciations[reverse] = (depreciatiableAmount * (i + 1)) / sumOfYears; reverse++; } WriteLine("==============================================="); WriteLine("Year Fraction Depreciation"); WriteLine("-----------------------------------------------"); for (int i = 0; i <= @estimatedLife - 1; i++) { WriteLine("{0,3}{1,15}{2,20}", year, fractions[i], Ceiling(@depreciations[i])); WriteLine("-----------------------------------------------"); year++; } WriteLine("==============================================="); } } <h1 class="bold common-font text-center">Machine Depreciation - Straight-Line Method</h1> <hr /> <form name="PayrollEvaluation" method="post" class="common-font"> <table align="center" style="width: 350px" class="table"> <tr> <td style="width: 150px" class="bold">Machine Cost:</td> <td><input type="text" style="" id="txtMachineCost" name="txtMachineCost" value="@machineCost" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Salvage Value:</td> <td><input type="text" id="txtSalvageValue" name="txtSalvageValue" value="@salvageValue" class="form-control text-based" /></td> <td> </td> </tr> <tr> <td class="bold">Estimated Life:</td> <td><input type="text" id="txtEstimatedLife" name="txtEstimatedLife" value="@estimatedLife" class="form-control text-based" /></td> <td>years</td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Calculate Depreciation" name="btnCalculate" style="width: 200px" /></td> </tr> </table> <hr /> <table style="width: 350px" align="center" class="common-font table"> <tr> <td class="bold">Depreciable Amount:</td> <td>@strDepreciableAmount</td> </tr> </table> <hr /> @{ year = 1; reverse = 0; depreciations = new double[estimatedLife]; fractions = new string[estimatedLife]; sumOfYears = (estimatedLife * (estimatedLife + 1)) / 2; for(int i = estimatedLife - 1; i >= 0; i--) { fractions[reverse] = (i + 1) + "/" + sumOfYears; depreciations[reverse] = (depreciatiableAmount * (i + 1)) / sumOfYears; reverse++; } } <table style="width: 525px" align="center" class="common-font table"> <tr> <td class="bold text-center">Year</td> <td class="bold text-center">Fraction</td> <td class="bold text-center">Depreciation</td> </tr> @for(int i = 0; i <= @estimatedLife - 1; i++) { <tr> <td class="text-center">@year</td> <td class="text-center">@fractions[i]</td> <td class="text-center">@Ceiling(@depreciations[i])</td> </tr> year++; } </table> </form>
Inseead of visiting the elements of a list by counting them, you may want to visit each item directly. To assist you with this, the C# language provides an operator named foreach. The formula to use it is:
foreach(variable in list) statement;
The loop starts with the foreach keyword followed by parentheses. In the parentheses, enter the list that contains the elements you want. Precede that list with an operator named in. The foreach loop needs a variable that would represent an item from the list. Therefore, in the parentheses, start by declaring a variable before the in operator. Of course, the variable declared by a data type and a name. Outside the parentheses, create a statement of your choice. At a minimum, you can simply display the variable's value to the user. Here is an example:
@page @model Exercises.Pages.ExerciseModel @using static System.Console @{ int[] numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 }; foreach (int n in numbers) WriteLine("Number: {0}", n); WriteLine("==============================="); }
This would produce:
Number: 102 Number: 44 Number: 525 Number: 38 Number: 6 Number: 28 Number: 24481 Number: 327 Number: 632 Number: 104 ===============================
You can declare the variable with the var or the dynamic keyword. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@{
string[] provinces = new[] { "Saskatchewan", "British Columbia",
"Ontario", "Alberta", "Manitoba" };
foreach (var administration in provinces)
WriteLine("Province: {0}", administration);
WriteLine("===============================");
}
You can include the statement inside curly brackets. This is especially useful if you to execute more than one statement. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@{
int i = 0;
string[] provinces = new[] { "Saskatchewan", "British Columbia",
"Ontario", "Alberta", "Manitoba" };
var capitals = new string[] {" Regina", "Victoria",
"Toronto", "Edmonton", "Heather Stefanson" };
foreach (dynamic administration in provinces)
{
System.Console.Write("Province: {0} ", administration);
System.Console.WriteLine("(Capital: {0})", capitals[i]);
i++;
}
System.Console.WriteLine("================================================");
}
This would produce:
Province: Saskatchewan (Capital: Regina) Province: British Columbia (Capital: Victoria) Province: Ontario (Capital: Toronto) Province: Alberta (Capital: Edmonton) Province: Manitoba (Capital: Heather Stefanson) ================================================
Controlling a Loop
Loops and Conditional Statement Nesting
You can create a conditional statement in the body of a loop. This is referred to as a nesting. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@{
int number = 0;
while (number < 5)
{
WriteLine("Make sure you review the time sheet before submitting it.");
if (number == 2)
WriteLine("This is the third warning about your time sheet.");
number++;
}
WriteLine("===============================================================");
}
This would produce:
Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. This is the third warning about your time sheet. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. ===============================================================
On the other hand, you can nest a loop in a conditional statement.
As mentioned in our introductions, a loop is supposed to navigate from a starting point to an ending value. Sometimes, for any reason, you want to stop that navigation before the end of the loop. To support this, the C-based languages, which include C#, provide the break keyword. The formula to use the break statement is:
break;
Although made of only one word, the break statement is a complete statement; therefore, it can (and should always) stay on its own line (this makes the program easy to read).
The break statement applies to the most previous conditional statement to it; provided that previous statement is applicable. The break statement can be used in a while condition, in a do...while, or a for loops to stop an ongoing operation. Here is an example that is used to count the levels of a house from 1 to 12 but it is asked to stop at 3:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@{
for (int number = 0; number <= 5; number++)
{
WriteLine("The time sheet was checked and this payroll has been approved.");
if (number == 2)
break;
}
WriteLine("===============================================================");
}
This would produce:
The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. ===============================================================
Continuing a Conditional Statement
Instead of stopping the flow of a loop, you may want to skip one of the values. To support this, the C-based languages such as C# provide the continue keyword. The formula to use it is:
continue;
When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, a do...while, or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line. Here is an example that is supposed to count the levels of a house from 1 to 6:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@{
string strNumbers = "";
for (int number = 0; number <= 5; number++)
{
if (number == 3)
continue;
strNumbers += number.ToString() + " ";
WriteLine("The list of numbers is {0}", strNumbers);
}
WriteLine("===========================================");
}
This would produce:
The list of numbers is 0 The list of numbers is 0 1 The list of numbers is 0 1 2 The list of numbers is 0 1 2 4 The list of numbers is 0 1 2 4 5 ===========================================
Notice that, when the compiler gets to 3, it ignores it.
Changing a Value in the Loop
Inside a loop, you may want to put a flag that would monitor the evolution of a piece of code so that, if a certain value is encountered, instead of skipping the looping by 1, you can make it jump to a valued range of your choice. To do this, in the loop, check the current value and if it gets to one you are looking for, change it. Here is an example where a loop is asked to count from 0 to 15:
@page @model Exercises.Pages.ExerciseModel @using static System.Console @{ string strNumbers = ""; for (int number = 0; number < 15; number++) { if (number == 6) number = 10; strNumbers += number.ToString() + " "; } WriteLine("The list of numbers is {0}", strNumbers); WriteLine("==========================================="); }
This would produce:
The list of numbers is 0 1 2 3 4 5 10 11 12 13 14 ===================================================
Notice that, when the loop reaches 6, it is asked to jump to number 10 instead.
Selecting a Value From a List
Introduction
If you have a list, such as an array, made of too many values, at one time you may want to isolate only the first n members of the list, or the last m members of the list, or a range of members from an index i to an index j. Another operation you may be interested to perform is to find out if a certain value exists in the list. One more interesting operation would be to find out what members or how many members of the list respond to a certain criterion.
for Looping
Consider the following array:
@{ int[] numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 }; }
Imagine you want to access only the first n members of the array. To do this, you can use an if conditional statement nested in a for loop. Here is an example that produces the first 4 values of the array:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@{
int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };
for (int i = 0; i < 10; i++)
if (i < 4)
WriteLine("Number: {0}", numbers[i]);
WriteLine("===============================");
}
This would produce:
Number: 102 Number: 44 Number: 525 Number: 38 ===============================
You can use the same technique to get the last m members of a list. You can also use a similar technique to get one or a few values inside of the list, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@{
int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };
for (int i = 0; i < 10; i++)
if (numbers[i] % 5 == 0)
WriteLine("Number: {0}", numbers[i]);
WriteLine("===============================");
}
This would produce:
Number: 525 ===============================
while(true)
For the different situations in which we used a while condition so far, we included a means of checking the condition. As an option, you can include juste the true Boolean constant in the parentheses of true. Here is an example:
@page
@model Exercise.Pages.ExerciseModel
@using static System.Console
@{
while (true)
WriteLine("Application development is fun!!!");
}
This type of statement is legal and would work fine, but it has no way to stop because it is telling the compiler "As long as 'this' is true, ...". The question is, what is "this"? As a result, the program would run for ever. Therefore, if you create a while(true) condition, in the body of the statement, you should (must) provide a way for the compiler to stop, that is, a way for the condition to be (or to become) false. This can be done by including an if condition. Here is an example:
@page
@model Exercise.Pages.ExerciseModel
@using static System.Console
@{
int i = 0;
while (true)
{
if (i > 8)
break;
WriteLine("Application development is fun!!!");
i++;
}
WriteLine("===============================");
}
This would produce:
Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! ===============================
Instead of using while(true), you can first declare and initialize a Boolean variable, or you can use a Boolean variable whose value is already known. The value can come from a method or by other means.
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2022, FunctionX | Friday 15 October 2021 | Next |
|