C# Loops
It's often necessary to perform a sequence of logic multiple times in a program. For example, there might be a list of some items where each item needs the same processing. This processing is performed with language constructs called loops. In C#, there are four types of loopsthe while loop, the do loop, the for loop, and the foreach loop. Each has its own benefits for certain tasks.
while Loops
If it's necessary to continually execute a group of statements while a condition is true, use the while loop. The general form of the while loop is as follows:
While (Boolean expression) [{] true condition statement(s) [}]
When the Boolean expression evaluates to true, the true condition statements are executed. The following example shows how a while loop can be used:
string doAgain = "Y"; int count = 0; string[] siteName = new string[10]; while (doAgain == "Y") { Console.Write("Please Enter Site Name: "); siteName[count++] = Console.ReadLine(); Console.Write("Add Another?: "); doAgain = Console.ReadLine(); }
A sneaky bug to watch out for with all loops is the empty statement bug. The following code is for illustrative purposes only, so don't try it:
string doAgain = "Y"; while (doAgain == "Y"); // loop forever { // this is never executed }
Because curly braces are optional, the semicolon after the Boolean expression represents the true condition statement. Thus, every time the Boolean expression evaluates to true, the empty statement is executed and the Boolean statement is evaluated againad infinitum.
The reason the curly braces don't cause a bug is because they represent a block, which is legal syntax in C#.
WARNING
A single semicolon is interpreted as a statement. A common mistake is to put a semicolon after a loop statement, which causes subsequent loop statements to execute only one time. These are hard-to-find errors.
do Loops
while loops evaluate an expression before executing the statements in a block. However, it may be necessary to execute the statements at least one time. This is what the do loop allows. Here's its general form:
do { Statement(s) } while (Boolean expression);
The statements execute, and then the Boolean expression is evaluated. If the Boolean expression evaluates to true, the statements are executed again. Otherwise, control passes to the statement following the entire do loop. The following is an example of a do loop in action:
do { Console.WriteLine(""); Console.WriteLine("A - Add Site"); Console.WriteLine("S - Sort List"); Console.WriteLine("R - Show Report\n"); Console.WriteLine("Q - Quit\n"); Console.Write("Please Choose (A/S/R/Q): "); choice = Console.ReadLine(); switch (choice) { case "a": case "A": Console.WriteLine("Add Site"); break; case "s": case "S": Console.WriteLine("Sort List"); break; case "r": case "R": Console.WriteLine("Show Report"); break; case "q": case "Q": Console.WriteLine("GoodBye"); break; default: Console.WriteLine("Huh??"); break; } } while ((choice = choice.ToUpper()) != "Q");
This code snippet prints a menu and then asks the user for input. For this purpose, it is logical to use a do loop because the menu has to print at least one time. If this were to be done with another type of loop, some artificial condition would have needed to be set just to get the first iteration.
for Loops
for loops are good for when the number of times to execute a group of statements is known beforehand. Here's its general syntax:
for (initializer; Boolean expression; modifier) [{] statement(s) [}]
The initializer is executed one time only, when the for loop begins. After the initializer executes, the Boolean expression is evaluated. The Boolean expression must evaluate to true for the statement(s) to be executed. Once the statement(s) have executed, the modifier executes and then the Boolean expression is evaluated again. The statement(s) continue to be executed until the Boolean expression evaluates to false, after which control transfers to the statement following the for loop. The following example illustrates how to implement a for loop:
int n = siteName.Length-2; int j, k; string save; for (k=n-1; k >= 0; k--) { j = k + 1; save = siteName[k]; siteName[n+1] = save; while ( String.Compare(save, siteName[j]) > 0 ) { siteName[j-1] = siteName[j]; j++; } siteName[j-1] = save; }
The insertion sort in this code shows how a for loop is used in a realistic scenario. Often, for loops begin at 0 and are incremented until a predetermined number of iterations have passed. This particular example starts at the end of the array and moves backward, decrementing each step. When k reaches 0, the loop ends.
For C++ Programmers
In Standard C++, for loop initializer declarations define a new scope for a variable with the same name in its enclosing block. In C#, this would be flagged as an error because a variable in the for loop initializer is not allowed to hide a variable with the same name in an enclosing block.
When programming in C#, there is a full set of libraries from which to choose premade functions. The Boolean condition of the while loop shows the String.Compare() method. In this particular instance, the program checks to see if save is greater than siteName[j]. If so, the Boolean result is true.
foreach Loops
The foreach loop is excellent for iterating through collections. Here's its syntax:
foreach (type identifier in collection) [{] statement(s) [}]
The type can be any C# or user-defined type. the identifier is the variable name that you want to use. The collection could be any C# collection object or array.
For C++ and Java Programmers
C++ and Java do not have a foreach loop.
Upon entering the foreach loop, the identifier variable is set with an item from the collection. Then the statement(s) are executed and control transfers back to get another item from the collection. When all items in the collection have been extracted, control transfers to the statement following the foreach loop.
Here's an example that iterates through the siteName array, printing each entry to the console.
foreach(string site in siteName) { Console.WriteLine("\t{0}", site); }
Had this been done with another loop, the program would have taken more effort. Then there's always the possibility of corrupting a counter. The foreach loop is a clean and simple way to iterate through an array.
The foreach loop was specially designed to work with collections. There are several collections in the System libraries, and Array is a built-in collection.