Chapter 6 - VB 2005 by Schneider 1
SampleDim i As Integer
For i = 1 To 5
lstTable.Items.Add(i & " " & i ^ 2)
Next
The loop control variable, i, is • Initialized to 1• Tested against the stop value, 5• Incremented by 1 at the Next statement
Chapter 6 - VB 2005 by Schneider 2
For…Next Loop Syntax
Uthaisombut & Schneider 3
Set control variableto initial value
ExecuteStatementsin loop body
Incrementcontrol variable
Is control variable >terminating value?
Executestatements
following the loop
Yes
No
Chapter 6 - VB 2005 by Schneider 4
Example 2
For index = 0 To n Step s
lstValues.Items.Add(index)
Next
Controlvariable
Startvalue
Stopvalue
Amountto add to
index
Chapter 6 - VB 2005 by Schneider 5
Example with Negative StepDim j As Integer
For j = 10 To 1 Step -1
lstBox.Items.Add(j)
Next
lstBox.Items.Add("Blastoff")
Chapter 6 - VB 2005 by Schneider 6
Declaration Inside For Statement
Dim i As Integer
For i = 1 To 5
lstTable.Items.Add(i & " " & i ^ 2)
Next
For i As Integer = 1 To 5
lstTable.Items.Add(i & " " & i ^ 2)
Next
Chapter 6 - VB 2005 by Schneider 7
Nested For…Next Loops
Chapter 6 - VB 2005 by Schneider 8
For and Next Pairs
• For and Next statements must be paired.
• If one is missing, the automatic syntax checker will complain with a wavy underline and a message such as
“A ‘For’ must be paired with a ‘Next’.”
Chapter 6 - VB 2005 by Schneider 9
Start, Stop, and Step values
• Consider a loop beginning with
For i As Integer = m To n Step s.
• The loop will be executed exactly once if m equals n no matter what value s has.
• The loop will not be executed at all if m is greater than n and s is positive,
or if m is less than n and s is negative.
Loop in Action
For i = 1 to 4
Picture1.print i * 2
Next
Chapter 6 - VB 2005 by Schneider 10
Loop in ActionFor i = 1 to 4
Picture1.print i * 2
Next
Chapter 6 - VB 2005 by Schneider 11
Value of i
Picture1 Output
Loop in ActionFor i = 1 to 4
Picture1.print i * 2
Next
Chapter 6 - VB 2005 by Schneider 12
Value of i
1
Picture1 Output
2
Loop in ActionFor i = 1 to 4
Picture1.print i * 2
Next
Chapter 6 - VB 2005 by Schneider 13
Value of i
2
Picture1 Output
2 4
Loop in ActionFor i = 1 to 4
Picture1.print i * 2
Next
Chapter 6 - VB 2005 by Schneider 14
Value of i
3
Picture1 Output
2 4 6
Loop in ActionFor i = 1 to 4
Picture1.print i * 2
Next
Chapter 6 - VB 2005 by Schneider 15
Value of i
4
Picture1 Output
2 4 6 8
Loop in Action
For i = 1 to 4
x = i mod 5
storeMe(i)
Picture1.print i * 2
Next
Chapter 6 - VB 2005 by Schneider 16
Top Related