Looping a Specific Number of Times Using forThe simplest type of loop to create is the for loop, which has been around since the earliest forms of the BASIC language. With a for loop, you instruct Visual C# to begin a loop by starting a counter at a specific value. Visual C# then executes the code within the loop, increments the counter by a defined incremental value, and repeats the loop until the counter reaches an upper limit you've set. The following is the syntax for the basic for loop: for ([initializers] ; [expression]; [iterator]) statement Initiating the Loop Using forThe for statement both sets up and starts the loop. The for statement has the components shown in Table 14.1.
The operator is used to specify the amount to increment or decrement the loop. Visual C# includes a number of operators, and they may seem foreign to you at first. An operator is like a shortcut for a math function. The following lists the most commonly used Visual C# operators and their effects:
The most common iterator used is loopvariable++, which increments the variable loopvariable by one. To decrement the counter variable by 1, you would use loopvariable--. To use a value other than 1 for the amount to change the loopvariable, you would use += (or -= for decrementing), followed by the value to increment (or decrement) the variable by, like this: loopvariable += 0.05. The following is a simple example of a for loop, followed by an explanation of what it's doing: for (int intCounter = 1; intCounter <= 100; intCounter++) Debug.WriteLine(intCounter); This for statement initializes an Integer named intCounter at 1; the condition intCounter <= 100 is tested and returns true; therefore, the statement debug.WriteLine(lngCounter) is executed. After the statement(s) are executed, the variable intCounter is incremented by one (intCounter++). This loop would execute 100 times, printing the numbers 1 through 100 to the Output debug window. By the Way To use the Debug object, you need to use the System.Diagnostics namespace. To execute multiple statements within a for loop, braces ({}) are used; a single-line for statement does not require braces. Here is the preceding for loop written to execute multiple statements: for (int intCounter = 1; intCounter <= 100; intCounter++) { Debug.WriteLine(intCounter); Debug.WriteLine(intCounter-1); } By the Way There may be times when you want to terminate a for loop before the expression evaluates to TRue. To exit a for loop at any time, use the break statement. Creating a for ExampleYou're now going to create a procedure containing a for loop that counts backward from 100 to 0 and sets opacity of a form to the value of the loop variable (the form will fade out). Create a new Windows Application named Fading Form and then follow these steps:
Your form should look like the one shown in Figure 14.1. Figure 14.1. This simple project does something pretty cool...
All that's left to do is to write the code. Double-click the button to access its Click() event and enter the following: for (double dblOpacity = 1; dblOpacity > 0; dblOpacity += -0.05) { this.Opacity = dblOpacity; // Let the form repaint itself. this.Refresh(); // Create a delay. System.Threading.Thread.Sleep(200); } // Show the form again. this.Opacity = 1; By the Way The code dblOpacity += -0.05 could also be written as dblOpacity -= 0.05. Much of this code should make sense to you by now. Here's what's happening:
Click Save All on the toolbar and press F5 to run the project. When the form first appears, it looks normal. Click the button, though, and watch the form fade out (see Figure 14.2)! Figure 14.2. This would take a lot of code without a loop!If you were to forgo a loop and write each line of code necessary to change the opacity, you would have to duplicate the statements 20 times each! Using a simple for loop, you performed the same task in just a few lines of code. Use a for loop when you know the number of times you want the loop to execute. This doesn't mean that you have to actually know the number of times you want the loop to execute at design time; it simply means that you must know the number of times you want the loop to execute when you first start the loop. You can use a variable to define any of the parameters for the for loop, as illustrated in the following code: int intUpperLimit=100; for (int intCounter=1; intCounter<=intUpperLimit;intCounter++) Debug.WriteLine(intCounter); Did you Know? One of the keys to writing efficient code is to eliminate redundancy. If you find yourself typing the same (or a similar) line of code repeatedly, chances are it's a good candidate for a loop. |