- Introduction
- Control Structures
- If/Then Selection Structure
- If/Then/Else Selection Structure
- While Repetition Structure
- DoWhile/Loop Repetition Structure
- DoUntil/Loop Repetition Structure
- Do/LoopWhile Repetition Structure
- Do/LoopUntil Repetition Structure
- Assignment Operators
- For/Next Repetition Structure
- Example: Using the For/Next Structure to Compute Compound Interest
- SelectCase Multiple-Selection Structure
- Using the Exit Keyword in a Repetition Structure
- Logical Operators
- Introduction to Windows Application Programming
- Summary
3.11 For/Next Repetition Structure
The For/Next repetition structure handles the details of counter-controlled repetition. The example in Fig. 3.3 uses the For/Next structure to display the even digits from 210.
Fig. 3.3 Counter-controlled repetition with the For Next structure.
The Main procedure of the program operates as follows: When the For/Next structure (lines 1214) begins its execution, the control variable counter is initialized to 2, thus addressing the first two elements of counter-controlled repetitioncontrol variable name and initial value. Next, the implied loop-continuation condition counter<=10 is tested. The To keyword is required in the For/Next structure. The optional Step keyword specifies the increment (i.e., the amount that is added to counter each time the body of the For/Next structure is executed). The increment of a For/Next structure could be negative, in which case it is a decrement, and the loop actually counts downwards. If Step and the value following it are omitted, the increment defaults to 1. Thus, programmers typically omit the Step portion for increments of 1.
Because, the initial value of counter is 2, the implied condition is satisfied (i.e., True), and the counter's value (2) is output in line 13. The required Nextkeyword marks the end of the For/Next repetition structure. When the Next keyword is reached, variable counter is incremented by the specified value of 2, and the loop begins again with the loop-continuation test.
At this point, the control variable is equal to 4. This value does not exceed the final value, so the program performs the body statement again. This process continues until the counter value of 10 has been printed and the control variable counter is incremented to 12, causing the loop-continuation test to fail and repetition to terminate. The program continues by performing the first statement after the For/Next structure. (In this case, procedure Main terminates, because the program reaches the EndSub statement on line 16.)