Zebra0.com

visual-basic loops

Step

The second format of a For loop specifies an increment:
For <variable> = <start value> to <end value> Step <increment>
<statements>
Next <variable>

Change the FOR loop statement as shown below, leave the rest the same.

     For Num = 5 To 25 Step 5

What do you expect to see in the list box?

When the For loop is executed the variable is assigned the starting value. Then the value is compared to the end value. If the increment is a positive number and the value is less than or equal to the end value, the statements in the body of the loop are executed, otherwise the next line after the loop is executed. If the increment is a negative number, then the value must be greater than or equal to the end value. After the statements in the body of the loop are executed, the next statement adds the increment to the variable and goes back to the top to check the value. The statements in a For loop may execute 0 or more times. If the starting value is past the end value it does not execute at all.

The example below does not generate anything because Num has a starting value that is greater than 1 and the increment is +1. (If you don't specify step size, the default is +1):
For Num = 10 To 1

You must specify a negative step size if the starting value is greater than the end value:
For Num = 10 To 1 Step –1

Modify the program to generate 10  9  8  7  6  5  4  3  2  1 Blast Off!

NEXT: For Loops