My space web page - 204 Control Structures: Part 2 Chapter 5 counter
204 Control Structures: Part 2 Chapter 5 counter = counter + 1 counter += 1 ++counter counter++ are equivalent in the increment portion of the for structure. Many programmers prefer the form counter++, because a for structure increments its control variable after the body of the loop executes and placing ++ after the variable name increments the variable after the program uses its value. Therefore, the postincrementing form seems more natural. Preincrementing and postincrementing have the same effect in the increment expression, because the increment does not appear in a larger expression. The two semicolons in the for structure are required. Common Programming Error 5.4 Using commas instead of the two required semicolons in a for header is a syntax error. Common Programming Error 5.5 Placing a semicolon immediately to the right of the right parenthesis of a for header makes the body of that for structure an empty statement. This is normally a logic error. The initialization, loop-continuation condition and increment portions of a for structure 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 forstructure may also be negative, in which case it is really a decrement, and the loop actually counts downward. If the loop-continuation condition is initially false, the program does not perform the body of the for structure. Instead, execution proceeds with the statement following the for structure. Programs frequently display the control variable value or use it in calculations in loop body. However, this use is not required. It is common to use the control variable for controlling repetition while never mentioning it in the body of the for structure. Testing and Debugging Tip 5.1 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. We flowchart the for structure much as we do the while structure. For example, the flowchart of the for statement for ( int counter = 1; counter <= 10; counter++ ) g.drawLine( 10, 10, 250, counter * 10 ); is shown in Fig. 5.4. This flowchart makes it clear that the initialization occurs only once and that the increment occurs each time after the program performs the body statement. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01