LoopsLoop constructs are all about executing code iteratively, and as you'd expect, C# supports the standard loops for , while , and do...while . It also includes another loop construct you might not expectthe foreach loop, which lets you loop over C# collections (coming up in Chapter 6) and arrays. We'll see all these loops in this chapter. The for LoopThe for loop is the most basic loop, and it's a programmer favorite. It simply executes a statement (or a block of statements) repeatedly until a test expression evaluates to false . Here's what it looks like: for ([ initializers ]; [ expression ]; [ iterators ]) statement Here are the parts of this statement:
In this statement, the initializers are evaluated first, and you can declare a loop variable that will keep track of the number of iterations there. When the expression evaluates to true , the statement(s) are executed and the iterators are evaluated. When expression becomes false , the loop terminates. Typically, the statement is a compound statement, enclosed in curly braces. You can see an example in ch02_01.cs, Listing 2.1. This program asks the user how many pats on the back they require and uses a for loop to display the text "Good work!" that many times. Note that this example declares the loop index variable, loopIndex , in the for loop's parentheses (which means, by the way, that it isn't available outside the loop). Listing 2.1 Using the for Loop (ch02_01.cs)class ch02_01 { static void Main() { System.Console.Write("How many pats on the back" + " do you require? "); int Max = int.Parse(System.Console.ReadLine()); for (int loopIndex = 1; loopIndex <= Max; loopIndex++) { System.Console.WriteLine("Good work!"); } } } Here's the output from ch02_01.cs: C:\>ch02_01 How many pats on the back do you require? 3 Good work! Good work! Good work! There are all kinds of for loops, of course. For example, because all the expressions in a for statement are optional, you can even omit them all to get an infinite loop: for(;;){} . You can also use multiple loop indices, like this: for(int x = 1, y = 2; x < 10 && y < 12; x++, y++){...} The while LoopAnother popular loop in C# is the while loop, which executes a statement (or a block of statements) until a specified expression evaluates to false . Here's what this loop looks like in C#: while ( expression ) statement Here are the parts of this statement:
While loops keep executing the statement as long as expression is true . Note that the test of expression takes place before execution of the loop, unlike the do...while loops (discussed next ). You can see an example, ch02_02.cs, in Listing 2.2. This program just prompts the user to type quit to quit, and uses a while loop to keep reading text until the user types quit. Listing 2.2 Using the while Loop (ch02_02.cs)class ch02_02 { static void Main() { System.Console.Write("Type quit to quit: "); string text = System.Console.ReadLine(); while (text != "quit") { System.Console.Write("Type quit to quit: "); text = System.Console.ReadLine(); } } } Here's what you see when you run this code: C:\>ch02_02 Type quit to quit: stop Type quit to quit: end Type quit to quit: terminate Type quit to quit: quit C:\> Note that because the loop's test is made at the beginning of the while loop, the code has to get the user's first response before even starting the loop, which means duplicating the code in the body of the loop outside the loop. You can fix that with a do...while loop, coming up next. The do...while LoopThe do...while loop executes a statement (or a block of statements) repeatedly until a specified expression evaluates to false . Unlike the while loop, it makes its test after the loop body is executed, so it always executes one or more times (that's the difference between these loops). Here's what the do...while loop looks like: do statement while ( expression ); Here are the parts of this statement:
You can convert the while example in Listing 2.2 to use the do...while loop, making the example much cleaner because you don't have to artificially summon the first response from the user before the loop begins. The new version appears in ch02_03.cs, Listing 2.3. Listing 2.3 Using the do...while Loop (ch02_03.cs)class ch02_03 { static void Main() { string text; do { System.Console.Write("Type quit to quit: "); text = System.Console.ReadLine(); } while (text != "quit"); } } This example gives the same results as the while example shown in ch02_02.cs. The foreach LoopThe foreach statement iterates over all members of a collection or array automatically. Here's what the foreach statement looks like: foreach ( type identifier in expression ) statement Here are the parts of this statement:
You use foreach to iterate over collections and arrays, and it's very handy, because it iterates over all elements in the collection or array automatically. You don't have to know how many elements there are and keep track of them with your own loop variable. Each time through the loop, identifier refers to the current element in the collection, giving you access to each element successively. For example, in the loop foreach (int element in collection) {...} , element will refer to the first item in collection in the first iteration, the second item in the second iteration, and so on. You can see an example in Listing 2.4, ch02_04.cs, which uses foreach to iterate over an array, displaying each element in the array.
Listing 2.4 Using the foreach Loop (ch02_04.cs)class ch02_04 { static void Main() { int[] array1 = {0, 1, 2, 3, 4, 5}; System.Console.Write("Here are the array elements: "); foreach (int element in array1) { System.Console.Write("{0} ", element); } } } Here's what you see when you run ch02_04. As you can see, foreach has iterated over all elements in the array: C:\>ch02_04 Here are the array elements: 0 1 2 3 4 5 The break and continue StatementsYou have more control over loops in C# using the break and continue statements. The break statement lets you break out of a loop, and the continue statement lets you skip to the next iteration of a loop. Say, for example, that you wanted to display the reciprocals (the reciprocal of 10 is 1/10) of various integers with a for loop, from 3 to 3. However, trying to take the reciprocal of 0 is a problem, because 1/0 is infinite (the result you'll get in C# is the constant NaN , "not a number"). To avoid taking the reciprocal of 0, you can use the break statement to break out of the loop, as you see in ch02_05.cs, Listing 2.5. Listing 2.5 Using the break Statement (ch02_05.cs)class ch02_05 { static void Main() { for(int loopIndex = -3; loopIndex <= 3; loopIndex++) { if(loopIndex == 0){ break; } System.Console.WriteLine("The reciprocal of {0} is {1}", loopIndex, 1/(float) loopIndex); } } } Here's what you see when you run this program: C:\>ch02_05 The reciprocal of -3 is -0.3333333 The reciprocal of -2 is -0.5 The reciprocal of -1 is -1 That's fine as far as it goes, but that's not very far. The loop simply ended when it encountered a value of 0. We can do better in this case with the continue statement, which just skips the troublesome 0 by continuing to the next iteration of the loop. You can see how this works in Listing 2.6, ch02_06.cs. Listing 2.6 Using the continue Statement (ch02_06.cs)class ch02_06 { static void Main() { for(int loopIndex = -3; loopIndex <= 3; loopIndex++) { if(loopIndex == 0){ continue; } System.Console.WriteLine("The reciprocal of {0} is {1}", loopIndex, 1/(float) loopIndex); } } } Here's what you see when you run ch02_06.cs. Note that the problematic reciprocal of 0 was skipped : C:\>ch02_06 The reciprocal of -3 is -0.3333333 The reciprocal of -2 is -0.5 The reciprocal of -1 is -1 The reciprocal of 1 is 1 The reciprocal of 2 is 0.5 The reciprocal of 3 is 0.3333333 The goto StatementThe goto statement has long been a pariah among programmers because of its capability to produce unstructured code, but it does have its uses (or it wouldn't have been included in C#). In fact, we saw the primary use for goto in Chapter 1, "Essential C#," where we used it in a switch statement to transfer control to another case statement: using System; class ch01_13 { static void Main() { Console.Write("Guess my number (1-5): "); int input = Convert.ToInt32(Console.ReadLine()); switch (input) { case 1: Console.WriteLine("Wrong, sorry.\n"); break; . . . case 4: goto case 1; . . . } } } You can use goto in these three forms in C#:
In the goto identifier form, you need to label a line of code with an identifier, followed by a colon . That looks like this: Top: System.Console.WriteLine("Welcome!"); . . . //Let's start over goto Top; The general use of goto in cases like this is, of course, strongly discouraged, because it creates unstructured spaghetti code code that jumps all over the place, which is very hard to deal with and debug. |