For…Next Statement

Introduction

The For…Next statement creates a loop that repeats a fixed number of times.

Syntax

For counter = start To end
statements
Next counter
counter is a numeric variable that will count beginning at start until it reaches end.

Look at the following example of an automatic greeter.

Example 1
Dim intStudent As Integer
For intStudent = 1 to 9
    MsgBox "Welcome to class.  Please sit in seat " & CStr(intStudent)
Next intStudent

What is the result of Example 1?

Step Keyword

The Step keyword changes how a For…Next loop counts. It can increment by 2, 0.5, or even count down.

Syntax

For counter = start To end Step increment
In this loop, counter will count from start to end, counting by increment.

Look at the following example of an automatic greeter when there is a quiz.

Example 2
Dim intStudent As Integer
For intStudent = 1 to 19 Step 2
    MsgBox "Welcome to class.  Please sit in seat " & CStr(intStudent)
Next intStudent

What is the result of Example 2? Why is Step 2 used?

Class Exercise: Factorial

Key Concept: How many different ways can 3 people sit down in 3 chairs? How many ways can 4 people be arranged? A factorial is a mathematical concept used to describe this concept. How is it calculated? What is 5!?

Create a program that calculates the factorial of any number.

  1. Begin by designing the form.
  2. Use the names txtInput, lblResult, cmdCalculate, cmdDone for the controls on the form.
  3. Add code to cmdDone.
  4. Add the code for cmdCalculate.

Factorial Code
Private Sub cmdCalculate_Click()
    ' dimension
    Dim intNumber As Integer
    Dim intCounter As Integer
    Dim dblResult As Double
    ' initialize variables
    intNumber = txtInput.Text
    dblResult = 1
    ' calculate result
    For intCounter = 1 To intNumber
        dblResult = dblResult * intCounter
    Next intCounter
    ' display result
    If dblResult < 1000000000 Then
        ' less than 1 billion, display with commas
        lblResult.Caption = CStr(intNumber) & "! = " & _
			Format(dblResult, "#,#")
    Else
        ' more than 1 billion, display in scientific
        lblResult.Caption = CStr(intNumber) & "! = " & _
			Format(dblResult, "Scientific")
    End If
End Sub

Private Sub cmdDone_Click()
‘ close program
Unload frmMain
End Sub

Assignment

The Divisor assignment is due in one week.