For-Next

The For-Next loop is used when you have a good idea of how many times the loop will execute.

In the first example below, we know that it will loop exactly 10 times. In the rest of the examples, we know the loop will execute as many times as the value of the variable.

In a For-Next loop, the looping variable, by default, always increments by 1. This will execute code as long as the condition is true.

Identify the three basic parts in the loops below:

  1. initialize
  2. test
  3. increment/decrement
Dim intLoop as Integer
Dim intTriangle as Integer
Dim intFactorial as Integer
Dim intSumOfOdds as Integer

For intLoop = 1 to 10
Next

For intLoop = 1 to intNumber
	'this loop will calculate the triangle value of a number
	intTriangle = intTriangle + intLoop
Next

For intLoop = 1 to intNumber
	'this loop will calculate the triangle value of a number
	' and the factorial value of a number
	intTriangle = intTriangle + intLoop
	intFactorial =intFactorial * intLoop
Next

For intLoop = 1 to intNumber Step 2
	'this loop will calculate the sum of the odd numbers
	intSumOfOdds = intSumOfOdds + intLoop
Next

For intLoop = intNumber to 1 Step -2
	'this loop will calculate the sum of the odd numbers
	'in reverse
	intSumOfOdds = intSumOfOdds + intLoop
Next