for Repetition Statement

Section 6.2 presented the essentials of counter-controlled repetition. The while statement can be used to implement any counter-controlled loop. C# also provides the for repetition statement, which specifies the elements of counter-controlled-repetition in a single line of code. Figure 6.2 reimplements the application in Fig. 6.1 using the for statement.

Figure 6.2. Counter-controlled repetition with the for repetition statement.

 1 // Fig. 6.2: ForCounter.cs
 2 // Counter-controlled repetition with the for repetition statement.
 3 using System;
 5 public class ForCounter
 6 {
 7 public static void Main( string[] args )
 8 {
 9 // for statement header includes initialization, 
10 // loop-continuation condition and increment 
11 for ( int counter = 1; counter <= 10; counter++ )
12  Console.Write( "{0} ", counter ); 
14 Console.WriteLine(); // output a newline
15 } // end Main
16 } // end class ForCounter
1 2 3 4 5 6 7 8 9 10

The application's Main method operates as follows: when the for statement (lines 1112) begins executing, control variable counter is declared and initialized to 1. (Recall from Section 6.2 that the first two elements of counter-controlled repetition are the control variable and its initial value.) Next, the application checks the loop-continuation condition, counter <= 10, which is between the two required semicolons. Because the initial value of counter is 1, the condition initially is true. Therefore, the body statement (line 12) displays control variable counter's value, which is 1. After executing the loop's body, the application increments counter in the expression counter++, which appears to the right of the second semicolon. Then the loop-continuation test is performed again to determine whether the application should continue with the next iteration of the loop. At this point, the control variable value is 2, so the condition is still true (the final value is not exceeded)and the application performs the body statement again (i.e., the next iteration of the loop). This process continues until the numbers 1 through 10 have been displayed and the counter's value becomes 11, causing the loop-continuation test to fail and repetition to terminate (after 10 repetitions of the loop body at line 12). Then the application performs the first statement after the forin this case, line 14.

Note that Fig. 6.2 uses (in line 11) the loop-continuation condition counter <= 10. If you incorrectly specified counter < 10 as the condition, the loop would iterate only nine timesa common logic error called an off-by-one error.

Common Programming Error 6 2

Using an incorrect relational operator or an incorrect final value of a loop counter in the loop-continuation condition of a repetition statement causes an off-by-one error.

Good Programming Practice 6 2

Using the final value in the condition of a while or for statement with the <= relational operator helps avoid off-by-one errors. For a loop that prints the values 1 to 10, the loop-continuation condition should be counter <= 10, rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is correct). Many programmers prefer so-called zero-based counting, in which to count 10 times, counter would be initialized to zero and the loop-continuation test would be counter < 10.

Figure 6.3 takes a closer look at the for statement in Fig. 6.2. The for's first line (including the keyword for and everything in parentheses after for)line 11 in Fig. 6.2is sometimes called the for statement header, or simply the for header. Note that the for header "does it all"it specifies each of the items needed for counter-controlled repetition with a control variable. If there is more than one statement in the body of the for, braces are required to define the body of the loop.

Figure 6.3. for statement header components.

The general format of the for statement is

for ( initialization; loopContinuationCondition; increment )

where the initialization expression names the loop's control variable and provides its initial value, the loopContinuationCondition is the condition that determines whether looping should continue and the increment modifies the control variable's value (whether an increment or decrement), so that the loop-continuation condition eventually becomes false. The two semicolons in the for header are required. Note that we don't include a semicolon after statement because the semicolon is already assumed to be included in the notion of a statement.

Common Programming Error 6 3

Using commas instead of the two required semicolons in a for header is a syntax error.

In most cases, the for statement can be represented with an equivalent while statement as follows:


while ( loopContinuationCondition )

In Section 6.7, we discuss a case in which a for statement cannot be represented with an equivalent while statement.

Typically, for statements are used for counter-controlled repetition, and while statements are used for sentinel-controlled repetition. However, while and for can each be used for either repetition type.

If the initialization expression in the for header declares the control variable (i.e., the control variable's type is specified before the variable name, as in Fig. 6.2), the control variable can be used only in that for statementit will not exist outside the for statement. This restricted use of the name of the control variable is known as the variable's scope. The scope of a variable defines where it can be used in an application. For example, a local variable can be used only in the method that declares the variable and only from the point of declaration through the end of the method. Scope is discussed in detail in Chapter 7, Methods: A Deeper Look.

Common Programming Error 6 4

When a for statement's control variable is declared in the initialization section of the for's header, using the control variable after the for's body is a compilation error.

All three expressions in a for header are optional. If the loopContinuationCondition is omitted, C# assumes that the loop-continuation condition is always true, thus creating an infinite loop. You can omit the initialization expression if the application initializes the control variable before the loopin this case, the scope of the control variable will not be limited to the loop. You can omit the increment expression if the application calculates the increment with statements in the loop's body or if no increment is needed. The increment expression in a for acts as if it were a stand-alone statement at the end of the for's body. Therefore, the expressions

counter = counter + 1
counter += 1

are equivalent increment expressions in a for statement. Many programmers prefer counter++ because it is concise and because a for loop evaluates its increment expression after its body executesso the postfix increment form seems more natural. In this case, the variable being incremented does not appear in a larger expression, so the prefix and postfix increment operators have the same effect.

Performance Tip 6 1

There is a slight performance advantage to using the prefix increment operator, but if you choose the postfix increment operator because it seems more natural (as in a for header), optimizing compilers will generate MSIL code that uses the more efficient form anyway.

Good Programming Practice 6 3

In many cases, the prefix and postfix increment operators are both used to add 1 to a variable in a statement by itself. In these cases, the effect is exactly the same, except that the prefix increment operator has a slight performance advantage. Given that the compiler typically optimizes your code to help you get the best performance, use the idiom (prefix or postfix) with which you feel most comfortable in these situations.

Common Programming Error 6 5

Placing a semicolon immediately to the right of the right parenthesis of a for header makes that for's body an empty statement. This is normally a logic error.

Error Prevention Tip 6 2

Infinite loops occur when the loop-continuation condition in a repetition statement never becomes false. To prevent this situation in a counter-controlled loop, ensure that the control variable is incremented (or decremented) during each iteration of the loop. In a sentinel-controlled loop, ensure that the sentinel value is eventually input.

The initialization, loop-continuation condition and increment portions of a for statement can contain arithmetic expressions. For example, assume that x = 2 and y = 10; if x and y are not modified in the body of the loop, then the statement

for ( int j = x; j <= 4 * x * y; j += y / x )

is equivalent to the statement

for ( int j = 2; j <= 80; j += 5 )

The increment of a for statement may also be negative, in which case it is a decrement, and the loop counts downward.

If the loop-continuation condition is initially false, the application does not execute the for statement's body. Instead, execution proceeds with the statement following the for.

Applications frequently display the control variable value or use it in calculations in the loop body, but this use is not required. The control variable is commonly used to control repetition without being mentioned in the body of the for.

Error Prevention Tip 6 3

Although the value of the control variable can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors.

The for statement's UML activity diagram is similar to that of the while statement (Fig. 5.4). Figure 6.4 shows the activity diagram of the for statement in Fig. 6.2. The diagram makes it clear that initialization occurs only once before the loop-continuation test is evaluated the first time, and that incrementing occurs each time through the loop after the body statement executes.

Figure 6.4. UML activity diagram for the for statement in Fig. 6.2.

Examples Using the for Statement



    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look


    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2


    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures



    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types


    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Similar book on Amazon

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