40 likes | 154 Views
Chapter Three Repetition Statements. All statements have been executed in order, from top to bottom, with two exceptions: the If, and Try/Catch statements that can cause certain statements to be skipped, depending on a certain condition.
E N D
Chapter Three Repetition Statements All statements have been executed in order, from top to bottom, with two exceptions: the If, and Try/Catch statements that can cause certain statements to be skipped, depending on a certain condition. We introduce the repetition statements, which are control statements that can repeat actions on a number of statements as long as a certain condition is True or False, depending on the structure. The For…Next Loop Structure In contrast to the Do…Loops, in which the number of repetitions of the loop body is unknown prior to processing, the For…Next Loop is used when we know the number of iterations of the loop in advance
The reserved word For marks the top of the loop, and the reserved word • Next marks its bottom. • The counter is a numeric variable that the programmer provides and that • the loop uses to count iterations. • Start, end, and increment are numeric expressions that the programmer • provides. Using the keyword • Step is optional. If you omit it, the counter is incremented by one after • each repetition, by default. • When the computer executes the For statement the first time: • The Start numeric value is stored in the variable counter. • The value stored in counter is compared to the ending value end, then • i- If the counter is greater than end, then the computer exits • the loop, and execution resumes at the statement following • the reserved word Next. • ii- If the counter is less than or equal to end, then the computerexecutes • the statements inside • the loop from top to bottom When the computer executes the Next • statement, it • Increases the value stored in counter by the value of increment. If the • keyword Step is omitted, • the counter is incremented by 1. • Execution goes back to the top of the loop.
Examples Using the For…Net Statement The following examples demonstrate different ways of varying the control variable “counter” in a For…Next statement i- Vary the control variable from 5 to 50 with increments of 2 ii- Vary the control variable i from 1 to 100 with increments of 1 For i = 1 To 100 Or For i = 1 To 100 Step 1 iii- Vary the control variable i from 10 to 2 with increments of -2 For i=10 to 2 step -2
iv- Vary the control variable i over the sequence 11, 13, 15, 17, and 19 For i = 11 To 19 Step 2 v- Vary the control variable i over the sequence 49, 42, 35, 28, and 21 For i = 49 To 21 Step -7 Good luck