Looping a Specific Number of Times Using for


Looping a Specific Number of Times Using for

The 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 for

The for statement both sets up and starts the loop. The for statement has the components shown in Table 14.1.

Table 14.1. Components of the for Statement

Part

Description

initializers

An expression that defines and initializes the loop variable.

expression

An expression that can be evaluated using Boolean logic. This expression is used to determine when to keep looping and when to terminate the loop.

operator

Expression statement that specifies how much to increment or decrement the loop variable.

statement

The embedded statement(s) to execute.


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:

  • ++ Increments the variable by one.

  • -- Decrements the variable by one.

  • += Adds the value on the right of the operator to the value on the left. For example, x += Y has the same result as X = X + Y.

  • -+ Subtracts the value on the right of the operator from the value on the left. For example, X -= Y has the same result as X = X Y.

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 Example

You'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:

1.

Right-click Form1.cs in the Solution Explorer, choose Rename, and change the name of the default form to frmFadingForm.cs. Next, set the form's Text property to Fading Form (you'll need to click the form once to access its design properties).

2.

Add a button to the form by double-clicking the Button item in the toolbox. Set the button's properties as follows:

Property

Value

Name

btnFadeForm

Location

105,113

Size

75,23

Text

Fade Form


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:

  • The first statement initializes the loop. It creates a variable of type double called dblOpacity. You have to use double because Opacity works with values of 0 to 1 and Integers don't support decimal places. The variable dblOpacity is initialed to 1, and the loop expression is defined as dblOpacity > 0. This means the loop will continue to execute as long as dblOpacity is greater than 0. Finally, the last section dictates that each time the loop completes, the variable dblOpacity is decremented by 0.05 (notice the negative sign in front of the value in code). All of this means that the loop will start at 1, and decrement the counter variable by .05 until the variable reaches 0, at which time the loop will no longer execute and code execution will jump to the first statement following the closing brace of the loop.

  • The second statement (after the opening brace for the loop code) sets the Opacity of the form to the value of the loop variable. The next line (after the comment) calls the Refresh() method of the form, which forces it to repaint itself. If you don't do this, Windows might not get around to repainting the form between iterations. Feel free to comment out the Refresh() statement (put a comment character in front of the statement so Visual C# treats it as a comment and doesn't execute it) to see what happens once you've successfully completed this example.

  • The next statement (the Sleep() statement) tells Visual C# to pause. The number in parentheses is the number of milliseconds to wait. In this case, 200. This is a nifty function! We could have used another for loop to create a pause, but then the duration of the pause would be dependent on the speed of the user's computer. By using Sleep(), we've guaranteed the pause to be the same on every machine that executes this code.

  • The closing brace sends execution back to the for statement, where the variable is decremented and tested to make sure that we haven't reached the stop value.

  • When the loop is finished, the form will be invisible. The last statement simply sets the Opacity property of the form back to 1, in effect showing the form.

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.





Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net