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 C# to begin a loop by starting a counter at a specific value. 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]; [iterators]) statement
The for statement both sets up and starts the loop. The for statement has the components shown in Table 15.1.
Part | Description |
---|---|
initializers | A comma-separated list of expressions or assignment statements to initialize the loop counters. |
expression | An expression that can be implicitly converted to boolean. The expression is used to test the loop-termination criteria. |
iterators | Expression statement(s) to increment or decrement the loop counters. |
statement | The embedded statement(s) to execute. |
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 (intCounter++). This loop would execute 100 times, printing the numbers 1 through 100 to the Output debug window.
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 statements does not require braces. Here is the previous for loop written to execute multiple statements:
for (int intCounter = 1; intCounter <= 100; intCounter++) { Debug.WriteLine(intCounter); Debug.WriteLine(intCounter-1); }
There may be times when you'll want to terminate a for loop before the expression evaluates to true. To exit a for loop at any time, use the break statement.
You're now going to create a method containing two for loops—one nested within the other. The first loop is going to count from 1 to 100 and set the Width property of a Label control to the current counter value; this will emulate a Windows progress meter. The second loop will be used to slow the execution of the first loop—an old programmer's trick using a for loop.
Create a new Windows Application named ForExample. Set the form's Text to For Statement Example. Add a Label control to the form by double-clicking the Label tool in the toolbox. Set the label's properties as follows:
Property | Value |
---|---|
Name | lblMeter |
BackColor | (Set to a light blue or any color you like.) |
Location | 100,100 |
Text | (make blank) |
Size | 100,17 |
Next, 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 | btnForLoop |
Location | 88,125 |
Size | 125,23 |
Text | Run a For Loop |
Your form should look like the one shown in Figure 15.1.
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 (int intLabelWidth=1; intLabelWidth<=100; intLabelWidth++) { lblMeter.Width = intLabelWidth; lblMeter.Refresh(); for (int intPauseCounter=1; intPauseCounter<=600000; intPauseCounter++); }
The first line starts the first for loop. It starts by creating and initializing the variable intLabelWidth; next comes an expression used to evaluate the variable, and the third part is the iterator, which increments intLabelWidth by one each time the loop completes.
The first statement within this for loop sets the width of the Label control to the value of intLabelWidth. The next statement calls the Refresh method of the Label control to ensure that it paints itself. Often, painting catches up when the CPU has idle time. Because you want the transition from a small label to a large one to be smooth, you need to make sure the label paints itself after each update to its Width property. After all the statements within the braces execute, intLabelWidth is incremented by one (intLabelWidth++) and the expression is evaluated once more. This means that the code within the loop will execute 100 times.
The next statement starts a second for loop using the intPauseCounter variable, creating and initializing intPauseCounter to 1 and setting the upper limit of the loop to 600,000. Following this for statement is a semicolon(;) with no statement before it. This creates an empty statement. Why is there no code for this for statement of the lngPauseCounter loop? This loop is used simply to create a delay within the processor. Most computers are so fast that if you didn't add a delay here, the first for loop would update the label's width from 1 to 100 so fast that you might not even see it update!
Click Save All on the toolbar and press F5 to run the project. The label starts with a width of 100. Click the button, and you'll see the label's width change to 1 and then increment to 100. If the speed is too slow or too fast, stop the project and adjust the upper limit of the inner for loop.
If you were to forgo a loop and write each and every line of code necessary to draw the label with a width from 1 to 100, it would take 100 lines of code. Using a simple for loop, you performed the same task in just a few lines. In addition, a for loop allowed you to create a pause during the update.
A for loop is best 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 arguments of the for loop, as illustrated in the following code:
int intUpperLimit=100; for (int intCounter=1; intCounter<=intUpperLimit;intCounter++) Debug.WriteLine(intCounter);
18.219.220.22