Looping a Specific Number of Times Using for Statements

   

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  

Initiating the Loop Using For

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

Table 15.1. Components of the for Statement
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.

graphics/bookpencil.gif

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); } 

Exiting a for Loop Early

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.

Building a for Loop Example

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.

Figure 15.1. This simple project will emulate a progress meter.

graphics/15fig01.jpg


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++); } 
graphics/bookpencil.gif

Using a loop to create a delay is actually a very poor and outdated coding technique. Other options can be used for creating a delay, such as calling System.Threading.Thread.Sleep(). This example is designed to illustrate nested loops ”which it does, not to show the best way to create a delay.



graphics/bookpencil.gif

Remember that C# is case sensitive. (Hint: for, int, and long are all lowercase).

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!

graphics/bookpencil.gif

I wrote this code on a 1.33GHz (1,333MHz) machine; you may have to alter this value if your processor speed is much different. If you have a slower CPU, reduce this value. If you have a much faster processor, increase this value. Wait until you test this code before making changes to the upper limit, however. Again, using another method, such as calling System.Threading.Thread.Sleep(), would allow precise control over the delay, regardless of the speed of the machine.

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); 
graphics/bulb.gif

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 in the same procedure, chances are it's a good candidate for a loop (and you may even want to place the duplicate code in its own method).


   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

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