Presentation is loading. Please wait.

Presentation is loading. Please wait.

For...Next Statements.

Similar presentations


Presentation on theme: "For...Next Statements."— Presentation transcript:

1 For...Next Statements

2 For...Next Syntax Repeats a group of statements a specified number of times. For counter = start To end [Step step] [statements] [Exit For] Next [counter] The counter can't be a Boolean or an array element. The step argument can be either positive or negative. After all statements in the loop have executed, step is added to counter. Any number of Exit For statements may be placed anywhere in the loop as an alternate way to exit. Exit For is often used after evaluating of some condition, for example If...Then, and transfers control to the statement immediately following Next.

3 For...Next Statement When the number of times a loop should be executed is known in advance, a For…Next loop should be used. For i = m To n statement(s) Next i control variable (counter) initial value terminating value body

4 For…Next Example Private Sub cmdDisplay_Click() Dim i As Integer
'Display a row of 10 stars picOutput.Cls For i = 1 To 10 picOutput.Print "*"; Next i End Sub

5 For…Next Example Private Sub cmdDisplay_Click()
Dim sum As Single, num As Integer sum = 0 For num = 1 To 99 Step 2 sum = sum + num Next num picOutput.Print "The sum is"; sum End Sub The subroutine calculates the sum of the odd numbers from 1 through 99.

6 Private Sub cmdReverse_Click()
Dim m As Integer, j As Integer Dim temp As String, strWord as String m = Len(txtWord.Text) strWord = txtWord.Text temp = "" For j = m To 1 Step -1 temp = temp & Mid(strWord, j, 1) Next j picTranspose.Print temp End Sub

7 Nested For...Next Example
Private Sub cmdDisplay_Click() Dim Words, Chars As Integer Dim MyString As String MyString = “” For Words = 10 To 1 Step -1 For Chars = 0 To 9 MyString = MyString & Chars Next Chars MyString = MyString & “ ” Next Words picOutput.Print MyString End Sub This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop.

8 Private Sub cmdDisplay_Click()
Dim j As Integer, k As Integer picTable.Cls For j = 1 To 4 For k = 1 To 4 picTable.Print j; "x"; k; "="; j * k, Next k picTable.Print Next j End Sub


Download ppt "For...Next Statements."

Similar presentations


Ads by Google