for Repetition Statement

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

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

 1 // Fig. 5.2: ForCounter.java
 2 // Counter-controlled repetition with the for repetition statement.
 3
 4 public class ForCounter
 5 {
 6 public static void main( String args[] )
 7 {
 8 // for statement header includes initialization, 
 9 // loop-continuation condition and increment 
10 for ( int counter = 1; counter <= 10; counter++ )
11  System.out.printf( "%d ", counter ); 
12
13 System.out.println(); // output a newline
14 } // end main
15 } // 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 1011) begins executing, the control variable counter is declared and initialized to 1. (Recall from Section 5.2 that the first two elements of counter-controlled repetition are the control variable and its initial value.) Next, the program 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 11) displays control variable counter's value, namely 1. After executing the loop's body, the program 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 program 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)thus, the program 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 11). Then the program performs the first statement after the forin this case, line 13.

Note that Fig. 5.2 uses (in line 10) the loop-continuation condition counter <= 10. If the programmer incorrectly specified counter < 10 as the condition, the loop would iterate only nine times. This mistake is a common logic error called an off-by-one error.

Common Programming Error 5.2

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

Good Programming Practice 5.2

Using the final value in the condition of a while or for statement and using 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 5.3 takes a closer look at the for statement in Fig. 5.2. The for's first line (including the keyword for and everything in parentheses after for)line 10 in Fig. 5.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 ({ and }) are required to define the body of the loop.

Figure 5.3. for statement header components.

(This item is displayed on page 184 in the print version)

The general format of the for statement is

 for ( initialization; loopContinuationCondition; increment )
 statement

where the initialization expression names the loop's control variable and provides its initial value, loopContinuationCondition is the condition that determines whether the loop should continue executing and increment modifies the control variable's value (possibly an increment or decrement), so that the loop-continuation condition eventually becomes false. The two semicolons in the for header are required.

Common Programming Error 5.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:


       initialization;

       while ( loopContinuationCondition )
       {
          statement
          increment;
       }

In Section 5.7, we show 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. 5.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 a program. 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 6, Methods: A Deeper Look.

Common Programming Error 5.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, Java assumes that the loop-continuation condition is always true, thus creating an infinite loop. You might omit the initialization expression if the program initializes the control variable before the loop. You might omit the increment expression if the program 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
 ++counter
 counter++

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 executes. Therefore, the postfix increment form seems more natural. In this case, the variable being incremented does not appear in a larger expression, so preincrementing and postincrementing actually have the same effect.

Performance Tip 5.1

There is a slight performance advantage to preincrementing, but if you choose to postincrement because it seems more natural (as in a for header), optimizing compilers will generate Java byte-code that uses the more efficient form anyway.

Good Programming Practice 5.3

In the most cases, preincrementing and postincrementing 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 preincrementing has a slight performance advantage. Given that the compiler typically optimizes your code to help you get the best performance, use the idiom with which you feel most comfortable in these situations.

Common Programming Error 5.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 5.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, 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 really a decrement, and the loop counts downward.

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

Programs 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 mentioning the control variable in the body of the for.

Error-Prevention Tip 5.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. 4.4). Figure 5.4 shows the activity diagram of the for statement in Fig. 5.2. The diagram makes it clear that initialization occurs 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 5.4. UML activity diagram for the for statement in Fig. 5.2.


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

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