Sams Teach Yourself C# in 24 Hours
- Table of Contents
- Copyright
- About the Authors
- Acknowledgments
- Tell Us What You Think!
- Introduction
- Audience and Organization
- Conventions Used in This Book
- Onward and Upward!
- Part I. The Visual Studio Environment
- Hour 1. A C# Programming Tour
- Hour 2. Navigating C#
- Hour 3. Understanding Objects and Collections
- Hour 4. Understanding Events
- Part II. Building a User Interface
- Hour 5. Building FormsPart I
- Hour 6. Building FormsPart II
- Hour 7. Working with the Traditional Controls
- Hour 8. Advanced Controls
- Hour 9. Adding Menus and Toolbars to Forms
- Hour 10. Drawing and Printing
- Part III. Making Things HappenProgramming!
- Hour 11. Creating and Calling Methods
- Hour 12. Using Constants, Data Types, Variables, and Arrays
- Hour 13. Performing Arithmetic, String Manipulation, and Date/Time Adjustments
- Hour 14. Making Decisions in C# Code
- Hour 15. Looping for Efficiency
- Looping a Specific Number of Times Using for Statements
- Using dowhile to Loop an Indeterminate Number of Times
- Summary
- Q&A
- Workshop
- Hour 16. Debugging Your Code
- Hour 17. Designing Objects Using Classes
- Hour 18. Interacting with Users
- Part IV. Working with Data
- Hour 19. Performing File Operations
- Hour 20. Controlling Other Applications Using Automation
- Hour 21. Working with a Database
- Part V. Deploying Solutions and Beyond
- Hour 22. Deploying a Solution
- Hour 23. Introduction to Web Development
- Hour 24. The 10,000-Foot View
- Appendix A. Answers to Quizzes/Exercises
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.
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.
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);
Using dowhile to Loop an Indeterminate Number of Times | Next Section

Account Sign In
View your cart