Counting and Looping
Counting and Looping
Introduction to Counting and Looping
Overview
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:
Practical Learning: Introducing Looping
body { margin: 0; padding: 0; } #top-banner { top: 0; width: 100%; height: 3em; background-color: #113d8b; border: 0px dashed #ff6a00; } #top-tool-range { padding-top: 8px; margin: auto; width: 500px; } .top-menu-item { margin-top: 5px; padding-top: 25px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px; width: 120px; color: azure; font-size: 1.18em; border: 1px solid #113d8b; } a.top-menu-item:hover { text-decoration: none; color: yellow; } .jumbotron { font-size: 18px; font-weight: 600; padding-top: 10px; padding-bottom: 10px; background-color: #5da2cf; } .jumbotron h1 { font-size: 41px; color: antiquewhite; } .jumbotron h2 { font-size: 31px; color: #d7d893; } .jumbotron p { font-size: 21px; color: ghostwhite; } .container .jumbotron { border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-left-radius: 15px; border-bottom-right-radius: 15px; } .depreciation { width: 400px; margin: auto; } .small-text { width: 60px; } .medium-text { width: 80px } .left-col { width: 150px; } .accentuate { font-weight: 600; }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SweetStarClothiers4.Controllers { public class DepreciationsController : Controller { // GET: Depreciations public ActionResult Index() { return View(); } // GET: StraightLineMethod public ActionResult StraightLineMethod() { return View(); } // GET: DoubleDecliningBalance public ActionResult DoubleDecliningBalance() { return View(); } // GET: SumOfTheYearsDigits public ActionResult SumOfTheYearsDigits() { return View(); } } }
@{ ViewBag.Title = "Straight-Line Method"; } <h2 class="text-center">Straight-Line Method</h2> @{ int estimatedLife = 5; decimal machineCost = 17000; decimal salvageValue = 2000; decimal depreciationRate = 0; decimal yearlyDepreciation = 0; decimal depreciatiableAmount = 0; if (IsPost) { machineCost = Request["txtMachineCost"].AsDecimal(); salvageValue = Request["txtSalvageValue"].AsDecimal(); estimatedLife = Request["txtEstimateLife"].AsInt(); depreciatiableAmount = machineCost - salvageValue; depreciationRate = 100 / estimatedLife; yearlyDepreciation = depreciatiableAmount / estimatedLife; } } <div class="depreciation"> @using (Html.BeginForm()) { <table> <tr> <td class="accentuate left-col">Machine Cost:</td> <td>@Html.TextBox("txtMachineCost", @machineCost)</td> </tr> <tr> <td class="accentuate">Salvage Value:</td> <td>@Html.TextBox("txtSalvageValue", @salvageValue)</td> </tr> <tr> <td class="accentuate">Estimate Life:</td> <td>@Html.TextBox("txtEstimateLife", @estimatedLife, new { @class = "small-text" }) Yearrs</td> </tr> <tr> <td> </td> <td><input name="btnCalculate" type="submit" value="Calculate" /></td> </tr> <tr> <td class="accentuate">Depreciation Rate:</td> <td>@Html.TextBox("txtDepreciation", @depreciationRate, new { @class = "small-text" }) %</td> </tr> <tr> <td class="accentuate">Depreciable Amount:</td> <td>@Html.TextBox("txtDepreciableAmount", @depreciatiableAmount)</td> </tr> <tr> <td class="accentuate">Yearly Depreciation:</td> <td>@Html.TextBox("txtDepreciation", @yearlyDepreciation)</td> </tr> </table> } </div>
@{ ViewBag.Title = "Double-Declining Balance"; } <h2 class="text-center">Depreciation: Double-Declining Balance</h2> @{ int estimatedLife = 5; double depreciation = 0; double decliningRate = 0; double machineCost = 17000; double salvageValue = 2000; if (IsPost) { machineCost = double.Parse(Request["txtMachineCost"]); salvageValue = int.Parse(Request["txtSalvageValue"]); estimatedLife = int.Parse(Request["txtEstimateLife"]); decliningRate = (100.00 / estimatedLife) * 2.00; depreciation = machineCost * decliningRate / 100.00; } } @using (Html.BeginForm()) { <div class="depreciation"> <table> <tr> <td class="left-col accentuate">@Html.Label("txtMachineCost", "Machine Cost:", new { @class = "strong" })</td> <td>@Html.TextBox("txtMachineCost", @machineCost, new { @class = "strong small-text" })</td> </tr> <tr> <td class="accentuate">@Html.Label("txtSalvageValue", "Salvage Value:", new { @class = "strong" })</td> <td>@Html.TextBox("txtSalvageValue", @machineCost)</td> </tr> <tr> <td class="accentuate">@Html.Label("txtEstimateLife", "Estimate Life:", new { @class = "strong" })</td> <td>@Html.TextBox("txtEstimateLife", @estimatedLife, new { @class = "strong small-text" }) Years</td> </tr> <tr> <td> </td> <td><input name="btnCalculate" type="submit" value="Calculate" /></td> </tr> <tr> <td class="accentuate">@Html.Label("txtDecliningRate", "Declining Rate:", new { @class = "strong small-text" })</td> <td>@Html.TextBox("txtDecliningRate", @decliningRate, new { @class = "strong small-text" }) %</td> </tr> <tr> <td class="accentuate">@Html.Label("txtDepreciation", "Depreciation First Year:", new { @class = "strong" })</td> <td>@Html.TextBox("txtDepreciation", @depreciation)</td> </tr> </table> </div> }
@{ ViewBag.Title = "Sum-of-the-Year's Digits"; } <h2>Sum-of-the-Year's Digits</h2> @{ int estimatedLife = 5; double machineCost = 17000; double salvageValue = 2000; double depreciatiableAmount = 0; if (IsPost) { machineCost = Convert.ToDouble(Request["txtCost"]); salvageValue = Convert.ToDouble(Request["txtSalvageValue"]); estimatedLife = Convert.ToInt32(Request["txtEstimateLife"]); depreciatiableAmount = machineCost - salvageValue; } } <div class="depreciation"> @using (Html.BeginForm()) { <table> <tr> <td class="accentuate left-col">Machine Cost:</td> <td>@Html.TextBox("txtCost", @machineCost)</td> </tr> <tr> <td class="accentuate">Salvage Value:</td> <td>@Html.TextBox("txtSalvageValue", @salvageValue)</td> </tr> <tr> <td class="accentuate">Estimate Life:</td> <td>@Html.TextBox("txtEstimateLife", @estimatedLife, new { @class = "small-text" }) Yearrs</td> </tr> <tr> <td> </td> <td><input name="btnCalculate" type="submit" value="Calculate" /></td> </tr> <tr> <td class="accentuate">Depreciable Amount:</td> <td>@Html.TextBox("txtDepreciatiableAmount", @depreciatiableAmount)</td> </tr> </table> } </div>
@{ ViewBag.Title = "Introduction"; } <div class="jumbotron"> <h1>Sweet Star Clothiers</h1> <h2>Business Machines</h2> <p class="lead"> This is the website from which the Sweet Star Clothiers company evaluates the evolutionary life span of its machines. To conduct its day-to-day operations, the company owns or rents a few business machines such as industrial sewing machines, fabric care machines, etc. On this internal website, the company perfoms various types of calculations with regards to machine maintenance and/or planning for machine replacement. </p> @Html.ActionLink("Get more information from SSC Management", "Index", "Depreciations", null, new { @class = "btn btn-primary btn-lg" }) </div> <div class="row"> <div class="col-md-4"> <h2>Straight-Line Method</h2> <p> In this section, for both business and legal purpose, SSC demonstrates how its management teacm calculates the depreciation of its machines using the Straight-Line Method. </p> @Html.ActionLink("Straight-Line Method", "StraightLineMethod", "Depreciations", null, new { @class = "btn btn-default" }) » </div> <div class="col-md-4"> <h2>Double-Declining Balance</h2> <p> This mode of evaluation allows SSC to get more values using a technique based on a fast-depreciating approach. In fact the depreciation rate used here is double that of the Straight-Line Method. </p> @Html.ActionLink("Double-Declining Balance", "DoubleDecliningBalance", "Depreciations", null, new { @class = "btn btn-default" }) » </div> <div class="col-md-4"> <h2>Sum-of-the-Year's Digits</h2> <p> Sometimes SSC uses the Sum-of-the-Year's Digits technique to evaluate the depreciation of its machines. This algorythm uses a series of fractions that have a common denominator. </p> @Html.ActionLink("Sum-of-the-Year's Digits", "SumOfTheYearsDigits", "Depreciations", null, new { @class = "btn btn-default" }) » </div> </div>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sweet Star Clothiers :: @ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") <link rel="stylesheet" type="text/css" href="~/Content/StarClothiers.css" /> </head> <body> <div id="top-banner"> <div id="top-tool-range"> @Html.ActionLink("Home", "Index", "Home", null, new { @class = "top-menu-item" }) @Html.ActionLink("Depreciations", "Index", "Depreciations", new { value = "Nothing" }, new { @class = "top-menu-item" }) @Html.ActionLink("About SSC", "About", "Home", null, new { @class = "top-menu-item" }) @Html.ActionLink("Contact Us", "Contact", "Home", null, new { @class = "top-menu-item" }) </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <h4 class="text-center">© @DateTime.Now.Year -- Sweet Star Clothiers</h4> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
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 in a method of a class where you want to add it and click Insert Snippet... Double-click Visual C#. In the list, double-click while.
If you are writing your code in a webpage, start the statement with the @ symbol. Also, the statement(s) must be included in curly brackets:
@while(condition) { statement };
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.
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 provides a starting value. From there, you canask the compiler to check another condition and keep doing something as long as that condition is true. Here is an example:
@{ // Consider a starting value as 0 int number = 0; } @while (number <= 5) { // As long as the above value is lower than 5, ... // ... display that number <p>Make sure you review the time sheet before submitting it.</p> // Increase the number (or counter) number++; // Check the number (or counter again. Is it still less than 4? }
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:
@{
int number = 5;
}
@while (number <= 4)
{
<p>Make sure you review the time sheet before submitting it.</p>
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 seen in the previous lesson, 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. Here is an example of accessing it:
@{
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
<p>Number of Items: @numbers.Length</p>
Each item can be located by its index from 0 to Number of Items - 1. Here is an example that access each of the items:
@{ double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; } <p>Number: @numbers[0]</p> <p>Number: @numbers[1]</p> <p>Number: @numbers[2]</p> <p>Number: @numbers[3]</p> <p>Number: @numbers[4]</p>
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:
@{ int counter = 0; double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; } @while (counter <= 4) { <p>Number: @numbers[counter]</p> counter++; }
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:
@{
int counter = 0;
Random rndNumber = new Random();
double[] numbers = new double[5];
}
@while (counter <= 4)
{
numbers[counter] = rndNumber.Next(1001, 9999);
counter++;
}
@{ counter = 0; }
@while (counter <= 4)
{
<p>Number: @numbers[counter]</p>
counter++;
}
Practical Learning: Introducing Loops in Lists
@{
ViewBag.Title = "Straight-Line Method";
}
<h2 class="text-center">Straight-Line Method</h2>
@{
int estimatedLife = 5;
decimal machineCost = 17000;
decimal salvageValue = 2000;
decimal depreciationRate = 0;
decimal yearlyDepreciation = 0;
decimal depreciatiableAmount = 0;
if (IsPost)
{
machineCost = Request["txtMachineCost"].AsDecimal();
salvageValue = Request["txtSalvageValue"].AsDecimal();
estimatedLife = Request["txtEstimateLife"].AsInt();
depreciatiableAmount = machineCost - salvageValue;
depreciationRate = 100 / estimatedLife;
yearlyDepreciation = depreciatiableAmount / estimatedLife;
}
}
<div class="depreciation">
@using (Html.BeginForm())
{
<table>
<tr>
<td class="accentuate left-col">Machine Cost:</td>
<td>@Html.TextBox("txtMachineCost", @machineCost)</td>
</tr>
<tr>
<td class="accentuate">Salvage Value:</td>
<td>@Html.TextBox("txtSalvageValue", @salvageValue)</td>
</tr>
<tr>
<td class="accentuate">Estimate Life:</td>
<td>@Html.TextBox("txtEstimateLife", @estimatedLife, new { @class = "small-text" }) Yearrs</td>
</tr>
<tr>
<td> </td>
<td><input name="btnCalculate" type="submit" value="Calculate" /></td>
</tr>
<tr>
<td class="accentuate">Depreciation Rate:</td>
<td>@Html.TextBox("txtDepreciation", @depreciationRate, new { @class = "small-text" }) %</td>
</tr>
<tr>
<td class="accentuate">Depreciable Amount:</td>
<td>@Html.TextBox("txtDepreciableAmount", @depreciatiableAmount)</td>
</tr>
<tr>
<td class="accentuate">Yearly Depreciation:</td>
<td>@Html.TextBox("txtDepreciation", @yearlyDepreciation)</td>
</tr>
</table>
}
<hr />
@{
int i = 1;
int year = 1;
decimal[] bookValues = new decimal[estimatedLife + 1];
bookValues[0] = machineCost;
while (i <= @estimatedLife - 1)
{
bookValues[i] = bookValues[i - 1] - yearlyDepreciation;
i++;
}
i = 0;
bookValues[estimatedLife] = salvageValue;
}
<table style="width: 500px" border="5">
<tr>
<td class="accentuate text-center">Year</td>
<td class="accentuate text-center">Book Value</td>
<td class="accentuate text-center">Accumulated Distribution</td>
</tr>
@while (i <= @estimatedLife - 1)
{
decimal accumulatedDepreciation = yearlyDepreciation * year;
<tr>
<td class="text-center small-text">@year</td>
<td class="text-center">@bookValues[i]</td>
<td class="text-center">@accumulatedDepreciation</td>
</tr>
i++;
year++;
}
</table>
</div>
Machine Cost: 8500 Salvage Value: 1500 Estimated Life 10
do This 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 while keywords used in a formula as follows:
do statement while (condition);
If the condition is written directly in a webpage, you should start it with an @ symbol. Also, the statement(s) must be included inside curly brackets:
do { statement } while (condition);
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.
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 "}". Here is an example:
@{ int number = 0; } @do { <p>Make sure you review the time sheet before submitting it.</p> number++; } while (number <= 4);
Practical Learning: doing Something while a Condition is True
@{
ViewBag.Title = "Double-Declining Balance";
}
<h2 class="text-center">Double-Declining Balance</h2>
@{
int estimatedLife = 5;
double depreciation = 0;
double salvageValue = 0;
double decliningRate = 0;
double machineCost = 17000;
if (IsPost)
{
machineCost = double.Parse(Request["txtMachineCost"]);
salvageValue = int.Parse(Request["txtSalvageValue"]);
estimatedLife = int.Parse(Request["txtEstimateLife"]);
decliningRate = (100.00 / estimatedLife) * 2.00;
depreciation = machineCost * decliningRate / 100.00;
}
}
@using (Html.BeginForm())
{
<div class="depreciation">
<table>
<tr>
<td class="left-col accentuate">@Html.Label("txtMachineCost", "Machine Cost:", new { @class = "strong" })</td>
<td>@Html.TextBox("txtMachineCost", @machineCost, new { @class = "strong small-text" })</td>
</tr>
<tr>
<td class="accentuate">@Html.Label("txtSalvageValue", "Salvage Value:", new { @class = "strong" })</td>
<td>@Html.TextBox("txtSalvageValue", @salvageValue)</td>
</tr>
<tr>
<td class="accentuate">@Html.Label("txtEstimateLife", "Estimate Life:", new { @class = "strong" })</td>
<td>@Html.TextBox("txtEstimateLife", @estimatedLife, new { @class = "strong small-text" }) Years</td>
</tr>
<tr>
<td> </td>
<td><input name="btnCalculate" type="submit" value="Calculate" /></td>
</tr>
<tr>
<td class="accentuate">@Html.Label("txtDecliningRate", "Declining Rate:", new { @class = "strong small-text" })</td>
<td>@Html.TextBox("txtDecliningRate", @decliningRate, new { @class = "strong small-text" }) %</td>
</tr>
<tr>
<td class="accentuate">@Html.Label("txtDepreciation", "Depreciation First Year:", new { @class = "strong" })</td>
<td>@Html.TextBox("txtDepreciation", @depreciation)</td>
</tr>
</table>
@{
int i = 1;
int year = 1;
double[] yearlyDepreciations = new double[estimatedLife];
double[] bookValuesEndOfYear = new double[estimatedLife];
double[] bookValuesBeginningOfYear = new double[estimatedLife];
// Year 1
bookValuesBeginningOfYear[0] = machineCost;
yearlyDepreciations[0] = machineCost * decliningRate / 100;
bookValuesEndOfYear[0] = machineCost - yearlyDepreciations[0];
// The other years
do
{
yearlyDepreciations[i] = bookValuesEndOfYear[i - 1] * decliningRate / 100;
bookValuesEndOfYear[i] = bookValuesEndOfYear[i - 1] - yearlyDepreciations[i];
bookValuesBeginningOfYear[i] = bookValuesEndOfYear[i - 1];
i++;
} while (i <= estimatedLife - 1);
i = 0;
}
<table style="width: 600px" border="6">
<tr>
<td class="accentuate small-text text-center">Year</td>
<td class="accentuate text-center">Book Value at Beginning of Year</td>
<td class="accentuate text-center">Depreciation for Year</td>
<td class="accentuate text-center">Book Value at End of Year</td>
</tr>
@do
{
<tr>
<td class="text-center">@year</td>
<td class="text-center">@System.Math.Ceiling(@bookValuesBeginningOfYear[i])</td>
<td class="text-center">@System.Math.Ceiling(@yearlyDepreciations[i])</td>
<td class="text-center">@System.Math.Ceiling(@bookValuesEndOfYear[i])</td>
</tr>
i++;
year++;
} while (i <= @estimatedLife - 1);
</table>
</div>
}
Machine Cost: 24680 Salvage Value: 0 Estimated Life 8
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CountriesStatistics03.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Mexico()
{
return View();
}
}
}
@{ ViewBag.Title = "United Mexican States"; } <h2>United Mexican States</h2> @{ string[] states = new string[31]; states[0] = "Guanajuato"; states[1] = "Tamaulipas"; states[2] = "Michoacán"; states[3] = "Coahuila"; states[4] = "Chihuahua"; states[5] = "Baja California Sur"; states[6] = "Nayarit"; states[7] = "Puebla"; states[8] = "Oaxaca"; states[9] = "Morelos"; states[10] = "Sonora"; states[11] = "Aguascalientes"; states[12] = "Baja California"; states[13] = "Tabasco"; states[14] = "Jalisco"; states[15] = "México"; states[16] = "Guerrero"; states[17] = "Colima"; states[18] = "Zacatecas"; states[19] = "Sinaloa"; states[20] = "Campeche"; states[21] = "Quintana Roo"; states[22] = "Nuevo León"; states[23] = "Hidalgo"; states[24] = "Tlaxcala"; states[25] = "Yucatán"; states[26] = "Querétaro"; states[27] = "Veracruz"; states[28] = "San Luis Potosí"; states[29] = "Durango"; states[30] = "Chiapas"; string[] capitals = new string[] { "Guanajuato", "Ciudad Victoria", "Morelia", "Saltillo", "Chihuahua", "La Paz", "Tepic", "Puebla de Zaragoza", "Oaxaca de Juárez", "Cuernavaca", "Hermosillo", "Aguascalientes", "Mexicali", "Villahermosa", "Guadalajara", "Toluca de Lerdo", "Chilpancingo de los Bravo", "Colima", "Zacatecas", "Culiacán", "San Francisco de Campeche", "Chetumal", "Monterrey", "Pachuca", "Tlaxcala", "Mérida", "Santiago de Querétaro", "Xalapa", "San Luis Potosí", "Victoria de Durango", "Tuxtla Gutiérrez"}; int[] areasSqrKms = new int[] { 30608, 80175, 58643, 151563, 247455, 73922, 27815, 34290, 93793, 4893, 179503, 5618, 71446, 24738, 78599, 22357, 63621, 5625, 75539, 57377, 57924, 42361, 64220, 20846, 3991, 39612, 11684, 71820, 60983, 123451, 73289 }; int[] areasSqrMiles = new int[] { 11818, 30956, 22642, 58519, 95543, 28541, 10739, 13240, 36214, 1889, 69306, 2169, 27585, 9551, 30347, 8632, 24564, 2172, 29166, 22153, 22365, 16356, 24800, 8049, 1541, 15294, 4511, 27730, 23546, 47665, 28297 }; int[] ordersOfAdmissionToFederation = new int[] { 2, 14, 5, 16, 18, 31, 28, 4, 3, 27, 12, 24, 29, 13, 9, 1, 21, 23, 10, 20, 25, 30, 15, 26, 22, 8, 11, 7, 6, 17, 19 }; }
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 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:
@for (int number = 0; number <= 5; number++) { <p>The time sheet was checked and this payroll has been approved.</p> }
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:
@{ int number; } @for (number = 0; number <= 5; number++) { <p>The time sheet was checked and this payroll has been approved.</p> }
Practical Learning: Counting for a Loop
@{
ViewBag.Title = "United Mexican States";
}
<h2>United Mexican States</h2>
@{
string[] states = new string[31];
states[0] = "Guanajuato"; states[1] = "Tamaulipas"; states[2] = "Michoacán"; states[3] = "Coahuila";
states[4] = "Chihuahua"; states[5] = "Baja California Sur"; states[6] = "Nayarit"; states[7] = "Puebla";
states[8] = "Oaxaca"; states[9] = "Morelos"; states[10] = "Sonora"; states[11] = "Aguascalientes";
states[12] = "Baja California"; states[13] = "Tabasco"; states[14] = "Jalisco"; states[15] = "México";
states[16] = "Guerrero"; states[17] = "Colima"; states[18] = "Zacatecas"; states[19] = "Sinaloa";
states[20] = "Campeche"; states[21] = "Quintana Roo"; states[22] = "Nuevo León"; states[23] = "Hidalgo";
states[24] = "Tlaxcala"; states[25] = "Yucatán"; states[26] = "Querétaro"; states[27] = "Veracruz";
states[28] = "San Luis Potosí"; states[29] = "Durango"; states[30] = "Chiapas";
string[] capitals = new string[] { "Guanajuato", "Ciudad Victoria", "Morelia", "Saltillo", "Chihuahua",
"La Paz", "Tepic", "Puebla de Zaragoza", "Oaxaca de Juárez", "Cuernavaca",
"Hermosillo", "Aguascalientes", "Mexicali", "Villahermosa", "Guadalajara",
"Toluca de Lerdo", "Chilpancingo de los Bravo", "Colima", "Zacatecas", "Culiacán",
"San Francisco de Campeche", "Chetumal", "Monterrey", "Pachuca",
"Tlaxcala", "Mérida", "Santiago de Querétaro", "Xalapa",
"San Luis Potosí", "Victoria de Durango", "Tuxtla Gutiérrez"};
int[] areasSqrKms = new int[] { 30608, 80175, 58643, 151563, 247455, 73922, 27815, 34290, 93793, 4893,
179503, 5618, 71446, 24738, 78599, 22357, 63621, 5625, 75539, 57377,
57924, 42361, 64220, 20846, 3991, 39612, 11684, 71820, 60983, 123451, 73289 };
int[] areasSqrMiles = new int[] { 11818, 30956, 22642, 58519, 95543, 28541, 10739, 13240, 36214, 1889,
69306, 2169, 27585, 9551, 30347, 8632, 24564, 2172, 29166, 22153,
22365, 16356, 24800, 8049, 1541, 15294, 4511, 27730, 23546, 47665, 28297 };
int[] ordersOfAdmissionToFederation = new int[] { 2, 14, 5, 16, 18, 31, 28, 4, 3, 27,
12, 24, 29, 13, 9, 1, 21, 23, 10, 20,
25, 30, 15, 26, 22, 8, 11, 7, 6, 17, 19 };
}
<table border="6" style="width: 660px" cellpadding="2" cellspacing="1">
<tr>
<td class="text-center"> </td>
<td> </td>
<td colspan="2" class="text-center"><b>Area</b></td>
<td class="text-center"><b>Admission to Federation</b></td>
<td> </td>
</tr>
<tr>
<td class="text-center short-text">#</td>
<td><b>State Name</b></td>
<td class="text-center"><b>Sqr Kms</b></td>
<td class="text-center"><b>Sqr Miles</b></td>
<td class="text-center"><b>Order</b></td>
<td><b>Capital</b></td>
</tr>
@for (int i = 0; i < states.Length; i++)
{
<tr>
<td class="text-center">@(i + 1)</td>
<td>@states[i]</td>
<td class="text-right">@areasSqrKms[i]</td>
<td class="text-right">@areasSqrMiles[i]</td>
<td class="text-center">@ordersOfAdmissionToFederation[i]</td>
<td>@capitals[i]</td>
</tr>
}
</table>
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
@{
ViewBag.Title = "Sum-of-the-Year's Digits";
}
<h2 class="text-center">Sum-of-the-Year's Digits</h2>
@{
int estimatedLife = 5;
double machineCost = 17000;
double salvageValue = 2000;
double depreciatiableAmount = 0;
if (IsPost)
{
machineCost = Convert.ToDouble(Request["txtCost"]);
salvageValue = Convert.ToDouble(Request["txtSalvageValue"]);
estimatedLife = Convert.ToInt32(Request["txtEstimateLife"]);
depreciatiableAmount = machineCost - salvageValue;
}
}
<div class="depreciation">
@using (Html.BeginForm())
{
<table>
<tr>
<td class="accentuate left-col">Machine Cost:</td>
<td>@Html.TextBox("txtCost", @machineCost)</td>
</tr>
<tr>
<td class="accentuate">Salvage Value:</td>
<td>@Html.TextBox("txtSalvageValue", @salvageValue)</td>
</tr>
<tr>
<td class="accentuate">Estimate Life:</td>
<td>@Html.TextBox("txtEstimateLife", @estimatedLife, new { @class = "small-text" }) Yearrs</td>
</tr>
<tr>
<td> </td>
<td><input name="btnCalculate" type="submit" value="Calculate" /></td>
</tr>
<tr>
<td class="accentuate">Depreciable Amount:</td>
<td>@Html.TextBox("txtDepreciatiableAmount", @depreciatiableAmount)</td>
</tr>
</table>
}
<hr />
@{
int year = 1;
int reverse = 0;
int sumOfYears = (estimatedLife * (estimatedLife + 1)) / 2;
double[] depreciations = new double[estimatedLife];
string[] fractions = new string[estimatedLife];
for(int i = estimatedLife - 1; i >= 0; i--)
{
fractions[reverse] = (i + 1) + "/" + sumOfYears;
depreciations[reverse] = (depreciatiableAmount * (i + 1)) / sumOfYears;
reverse++;
}
}
<table style="width: 400px" border="5">
<tr>
<td class="accentuate small-text text-center">Year</td>
<td class="accentuate text-center">Fraction</td>
<td class="accentuate text-center">Depreciation</td>
</tr>
@for(int i = 0; i <= @estimatedLife - 1; i++)
{
<tr>
<td class="text-center small-text">@year</td>
<td class="text-center">@fractions[i]</td>
<td class="text-center">@System.Math.Ceiling(@depreciations[i])</td>
</tr>
year++;
}
</table>
</div>
Machine Cost: 6850 Salvage Value: 500 Estimated Life 8
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:
@{
int number = 0;
while (number < 5)
{
<p>Make sure you review the time sheet before submitting it.</p>
if( number == 2 ) {
<p>This is the third warning about your time sheet.
}
number++;
}
}
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:
@{
for(int number = 0; number <= 5; number++)
{
<p>The time sheet was checked and this payroll has been approved.</p>
if (number == 2) {
break;
}
}
}
Continuing a Conditional Statement
Instead 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:
@{
string strNumbers = "";
for (int number = 0; number <= 5; number++)
{
if (number == 3) {
continue;
}
strNumbers += number.ToString() + " ";
<p>The list of numbers is " + strNumbers</p>
}
}
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:
@{ string strNumbers = ""; for (int number = 0; number < 15; number++) { if (number == 6) { number = 10; } strNumbers += number.ToString() + " " } <p>The list of numbers is " + strNumbers</p> }
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:
@{
int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };
for(int i = 0; i < 10; i++) {
if (i < 4) {
<p>Number: numbers[i]</p>
}
}
}
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:
@{
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) {
<p>Number: numbers[i]</p>
}
}
}
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:
@{ while(true) { <p>Web Development Programming is fun!!!</p> } }
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 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:
@{
int i = 0;
while (true)
{
if (i > 8)
{
break;
}
<p>Web Development Programming is fun!!!</p>
i++;
}
}
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-2019, FunctionX | Next |
|