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
using static System.Console; int estimatedLife = 0; double machineCost = 0.00; double salvageValue = 0.00; Title = "Depreciation: Straight-Line Method"; WriteLine("Enter the values for the machine depreciation"); try { Write("Machine Cost: "); machineCost = double.Parse(ReadLine()!); } 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 { Write("Salvage Value: "); salvageValue = double.Parse(ReadLine()!); } 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 { Write("Estimated Life (in Years): "); estimatedLife = int.Parse(ReadLine()!); } 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."); } double depreciatiableAmount = machineCost - salvageValue; 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 depreciationRate = 100 / estimatedLife; double yearlyDepreciation = depreciatiableAmount / estimatedLife; Clear(); 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("====================================");
Machine Cost: 22580 Salvage Cost: 3875 Estimated Life: 5
==================================== Depreciation - Straight-Line Method ------------------------------------ Machine Cost: 22580 Salvage Value: 3875 Estimate Life: 5 Years Depreciation Rate: 20% ------------------------------------ Depreciable Amount: 18705 Yearly Depreciation: 3741 ==================================== Press any key to close this window . . .
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;
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 . . . };
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 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:
// 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 Console.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. Press any key to continue . . .
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) { Console.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 of a list of numbers with each number stored in a variable:
public class Exercise
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 be 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:
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 ================================= Press any key to continue . . .
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:
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; Console.WriteLine("Number: {0}", numbers[0]); Console.WriteLine("Number: {0}", numbers[1]); Console.WriteLine("Number: {0}", numbers[2]); Console.WriteLine("Number: {0}", numbers[3]); Console.WriteLine("Number: {0}", numbers[4]); Console.WriteLine("============================");
This would produce:
Number: 12.44 Number: 525.38 Number: 6.28 Number: 2448.32 Number: 632.04 ============================ Press any key to continue . . .
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) { Console.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:
int counter = 0;
Random rndNumber = new Random();
int[] numbers = new int[] { 203, 81, 7495, 40, 9580 };
Console.WriteLine("====================================");
Console.WriteLine("Original List");
while (counter <= 4)
{
Console.WriteLine("Number: {0}", numbers[counter]);
counter++;
}
Console.WriteLine("-------------------------------------");
Console.WriteLine("Updating the numbers of the list...");
counter = 0;
while (counter <= 4)
{
numbers[counter] = rndNumber.Next(1001, 9999);
counter++;
}
Console.WriteLine("-------------------------------------");
counter = 0;
Console.WriteLine("Updated Numbers");
while (counter <= 4)
{
Console.WriteLine("Number: {0}", numbers[counter]);
counter++;
}
Console.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 ==================================== Press any key to continue . . .
Practical Learning: Introducing Loops in Lists
using static System.Console;
int estimatedLife = 0;
double machineCost = 0.00;
double salvageValue = 0.00;
Title = "Depreciation: Straight-Line Method";
WriteLine("Enter the values for the machine depreciation");
try
{
Write("Machine Cost: ");
machineCost = double.Parse(ReadLine()!);
}
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
{
Write("Salvage Value: ");
salvageValue = double.Parse(ReadLine()!);
}
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
{
Write("Estimated Life (in Years): ");
estimatedLife = int.Parse(ReadLine()!);
}
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.");
}
double depreciatiableAmount = machineCost - salvageValue;
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 depreciationRate = 100 / estimatedLife;
double yearlyDepreciation = depreciatiableAmount / estimatedLife;
Clear();
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:F}", yearlyDepreciation);
WriteLine("====================================");
int i = 1;
int year = 1;
double[] bookValues = new double[estimatedLife + 1];
bookValues[0] = machineCost;
while (i <= @estimatedLife - 1)
{
bookValues[i] = bookValues[i - 1] - yearlyDepreciation;
i++;
}
i = 0;
bookValues[estimatedLife] = salvageValue;
WriteLine(" Accumulated");
WriteLine("Year Book Value Distribution");
while (i <= estimatedLife - 1)
{
double accumulatedDepreciation = yearlyDepreciation * year;
WriteLine("------------------------------------");
WriteLine(" {0} {1, 10} {2, 12}", year, bookValues[i], accumulatedDepreciation);
i++;
year++;
}
WriteLine("====================================");
Machine Cost: 7448.85 Salvage Value: 955.50 Estimated Life: 5
==================================== Depreciation - Straight-Line Method ------------------------------------ Machine Cost: 7448.85 Salvage Value: 955.5 Estimate Life: 5 Years Depreciation Rate: 20% ------------------------------------ Depreciable Amount: 6493.35 Yearly Depreciation: 1298.67 ==================================== Accumulated Year Book Value Distribution ------------------------------------ 1 7448.85 1298.67 ------------------------------------ 2 6150.18 2597.34 ------------------------------------ 3 4851.51 3896.01 ------------------------------------ 4 3552.84 5194.68 ------------------------------------ 5 2254.17 6493.35 ==================================== Press any key to continue . . .
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. The formula to follow is:
do statement while (condition);
To make your code easy to read, especially if the condition is long, you can (and should) write the while condition section on its own line. This would be done as follows:
do statement while (condition);
If the statement involves 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 if 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 "}".
int number = 0; do { Console.WriteLine("Make sure you review the time sheet before submitting it."); number++; } while (number <= 4); Console.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. ========================================================== Press any key to continue . . .
Practical Learning: doing Something while a Condition is True
using static System.Math; using static System.Console; WriteLine("=-= Depreciation - Double Declining Balance =-="); WriteLine("-----------------------------------------------"); WriteLine("Provide the following values about the machine"); Write("Machine Cost: "); double machineCost = double.Parse(ReadLine()!); Write("Estimated Life: "); int estimatedLife = int.Parse(ReadLine()!); double decliningRate = (100.00 / estimatedLife) * 2.00; double depreciation = machineCost * decliningRate / 100.00; Clear(); 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}", depreciation); WriteLine("==========================================================="); 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.00; bookValuesEndOfYear[0] = machineCost - yearlyDepreciations[0]; // The other years do { yearlyDepreciations[i] = bookValuesEndOfYear[i - 1] * decliningRate / 100.00; bookValuesEndOfYear[i] = bookValuesEndOfYear[i - 1] - yearlyDepreciations[i]; bookValuesBeginningOfYear[i] = bookValuesEndOfYear[i - 1]; i++; } while (i <= estimatedLife - 1); i = 0; WriteLine(" Book Value at Book Value at"); WriteLine("Beginning of Year Depreciation for Year End of Year"); WriteLine("-----------------------------------------------------------"); do { WriteLine("{0,10}{1,22}{2,20}", year, Ceiling(@bookValuesBeginningOfYear[i]), Ceiling(@yearlyDepreciations[i]), Ceiling(@bookValuesEndOfYear[i])); WriteLine("-----------------------------------------------------------"); i++; year++; } while (i <= estimatedLife - 1);
=-= Depreciation - Double Declining Balance =-= =========================================================== Depreciation Estimation ----------------------------------------------------------- Machine Cost: 24,669.55 ----------------------------------------------------------- Estimated Life: 8 years ----------------------------------------------------------- Declining Rate: 25.00 ----------------------------------------------------------- Depreciation First Year: 6,167.39 =========================================================== Book Value at Book Value at Beginning of Year Depreciation for Year End of Year ----------------------------------------------------------- 1 24670 6168 ----------------------------------------------------------- 2 18503 4626 ----------------------------------------------------------- 3 13877 3470 ----------------------------------------------------------- 4 10408 2602 ----------------------------------------------------------- 5 7806 1952 ----------------------------------------------------------- 6 5855 1464 ----------------------------------------------------------- 7 4391 1098 ----------------------------------------------------------- 8 3293 824 ----------------------------------------------------------- Press any key to close this window . . .
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;
If the whole code you want to write is short, you can write the whole on one line. If the statement is long or you need many lines of code, in fact even if the statement is for one line of code, include it in curly brackets.
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:
for (int number = 0; number <= 5; number++)
Console.WriteLine("The time sheet was checked and this payroll has been approved.");
Console.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. =============================================================== Press any key to continue . . .
To make your code easy to read, you can put each par of the for expression on its own line. Here is an example:
for(int number = 0;
number <= 5;
number++)
Console.WriteLine("The time sheet was checked and this payroll has been approved.");
Console.WriteLine("===============================================================");
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++) Console.WriteLine("The time sheet was checked and this payroll has been approved."); Console.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:
span class="codered">int number = 0;
for (; number <= 5; number++)
Console.WriteLine("The time sheet was checked and this payroll has been approved.");
Console.WriteLine("===============================================================");
Practical Learning: Counting for a Loop
using static System.Math; using static System.Console; WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-="); WriteLine("----------------------------------------------"); WriteLine("Provide the following values about the machine"); Write("Machine Cost: "); double machineCost = double.Parse(ReadLine()!); Write("Salvage Value: "); double salvageValue = double.Parse(ReadLine()!); Write("Estimated Life: "); int estimatedLife = int.Parse(ReadLine()!); double depreciatiableAmount = machineCost - salvageValue; Clear(); 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("depreciatiable Amount: {0:N}", depreciatiableAmount); int year = 1; int counter = 0; int sumOfYears = (estimatedLife * (estimatedLife + 1)) / 2; double[] depreciations = new double[estimatedLife]; string[] fractions = new string[estimatedLife]; 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++; }
=-= Depreciation - Sum-of-the-Year's Digits =-= =============================================== Depreciation Estimation ----------------------------------------------- Machine Cost: 6,849.95 Salvage Value: 524.85 Estimated Life: 5 depreciatiable Amount: 6,325.10 =============================================== Year Fraction Depreciation ----------------------------------------------- 1 1/15 422 ----------------------------------------------- 2 2/15 844 ----------------------------------------------- 3 3/15 1266 ----------------------------------------------- 4 4/15 1687 ----------------------------------------------- 5 5/15 2109 ----------------------------------------------- Press any key to close this window . . .
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
using static System.Math; using static System.Console; WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-="); WriteLine("----------------------------------------------"); WriteLine("Provide the following values about the machine"); Write("Machine Cost: "); double machineCost = double.Parse(ReadLine()!); Write("Salvage Value: "); double salvageValue = double.Parse(ReadLine()!); Write("Estimated Life: "); int estimatedLife = int.Parse(ReadLine()!); double depreciatiableAmount = machineCost - salvageValue; Clear(); 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("depreciatiable Amount: {0:N}", depreciatiableAmount); 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++; } 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++; }
=-= Depreciation - Sum-of-the-Year's Digits =-= =============================================== Depreciation Estimation ----------------------------------------------- Machine Cost: 6,849.95 Salvage Value: 524.85 Estimated Life: 5 depreciatiable Amount: 6,325.10 =============================================== Year Fraction Depreciation ----------------------------------------------- 1 5/15 2109 ----------------------------------------------- 2 4/15 1687 ----------------------------------------------- 3 3/15 1266 ----------------------------------------------- 4 2/15 844 ----------------------------------------------- 5 1/15 422 ----------------------------------------------- Press any key to close this window . . .
Instead 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;
To make your code easy to read, you can (and should) write the statement on its own line. This can be done as follows:
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:
int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 }; foreach (int n in numbers) Console.WriteLine("Number: {0}", n); Console.WriteLine("===============================");
This would produce:
Number: 102 Number: 44 Number: 525 Number: 38 Number: 6 Number: 28 Number: 24481 Number: 327 Number: 632 Number: 104 =============================== Press any key to continue . . .
You can declare the variable with the var keyword. Here is an example:
using static System.Console;
string[] provinces = new string[] { "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.
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)
{
Console.WriteLine("Make sure you review the time sheet before submitting it.");
if (number == 2)
Console.WriteLine("This is the third warning about your time sheet.");
number++;
}
Console.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. =============================================================== Press any key to continue . . .
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++)
{
Console.WriteLine("The time sheet was checked and this payroll has been approved.");
if (number == 2)
break;
}
Console.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. =============================================================== Press any key to continue . . .
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:
string strNumbers = "";
for (int number = 0; number <= 5; number++)
{
if (number == 3)
continue;
strNumbers += number.ToString() + " ";
Console.WriteLine("The list of numbers is {0}", strNumbers);
}
Console.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 =========================================== Press any key to continue . . .
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() + " "; } Console.WriteLine("The list of numbers is {0}", strNumbers); Console.WriteLine("===========================================");
This would produce:
The list of numbers is 0 1 2 3 4 5 10 11 12 13 14 =================================================== Press any key to continue . . .
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)
Console.WriteLine("Number: {0}", numbers[i]);
Console.WriteLine("===============================");
This would produce:
Number: 102 Number: 44 Number: 525 Number: 38 =============================== Press any key to continue . . .
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)
Console.WriteLine("Number: {0}", numbers[i]);
Console.WriteLine("===============================");
This would produce:
Number: 525 =============================== Press any key to continue . . .
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. This would be done as follows:
while(true) statement;
If you have only one statement, you can write that statement on its own line. This would be done as follows:
while(true) statement;
Still in both cases, you can include the statement in curly brackets. If you have more than one statement, you must include them in curly brackets. This would be done as follows:
while(true) { statement}; while(true) { 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:
The result is:
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:
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:
int i = 0;
while (true)
{
if (i > 8)
break;
Console.WriteLine("Application development is fun!!!");
i++;
}
Console.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!!! =============================== Press any key to continue . . .
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-2023, FunctionX | Friday 15 October 2021 | Next |
|