JK VB NET 6 Repetition Structures Loops
JK VB NET 6 Repetition Structures Loops
• InputBox
• ListsBox
Revision Questions
Which type of loop is best to use when you know
exactly how many times the loop should repeat?
Which type of loop is best to use when you want
the loop to repeat as long as a condition exists?
Which type of loop is best to use when you want
the loop to repeat until a condition exists?
Slide 5- 2
Class Exercise
Slide 5- 3
Revision Questions
Write a program that will print out the following
pattern on the screen
Slide 5- 4
Introduction
This presentation covers the Visual Basic looping
statements
Do … While
Do … Until
For … Next
Input Boxes
Slide 5- 5
Input Boxes
1
Input Boxes Provide a Simple Way
to Gather Input Without Placing a
Text Box on a Form
Format of the InputBox Function
InputBox(Prompt [,Title] [,Default] [,Xpos] [,Ypos])
Slide 5- 7
Sample InputBox Usage
strUserInput = InputBox("Enter the distance.", _
"Provide a Value", "150")
Slide 5- 8
Xpos & Ypos
Xpos specifies the distance from the left of the
screen to the left side of the box
Ypos specified the distance from the top of the
screen to the top of the box
Both are specified in pixels
Slide 5- 9
List Boxes
2
List Boxes Display a List of Items
and Allow the User to Select an
Item From the List
The ListBox Control
A ListBox control displays a list of items and
allows the user to select one or more
Drag from Toolbox to create this control on a form
Slide 5- 11
ListBox Items Property
The Items property holds an entire list of values
from which the user may choose
The list of values may be established at run time
or as part of the form design
To set list values in the form design:
Select the list box in the Design window
Slide 5- 12
ListBox Items.Count Property
This property returns an integer with the number
of entries stored in the Items property
Example of use:
If lstEmployees.Items.Count = 0 Then
MessageBox.Show("The list has no items!")
End If
Slide 5- 13
Item Indexing
The Items property values can be accessed from
your VB code
Each item value is given a sequential index
The first item has an index of 0
Example:
name = lstCustomers.Items(2)
' Access the 3rd item value
Slide 5- 14
Index Out of Range Error
The index of the last item is always
list.Items.Count-1
Reference to an index greater than Count-1 or
less than zero throws an exception
An exception handler can trap this error
The variable ex captures the exception thrown
Try
strInput = lstMonths.Items(n).ToString()
Catch ex as Exception
MessageBox.show(ex.Message)
End Try
Slide 5- 15
ListBox SelectIndex Property
The SelectIndex property returns an integer with
the index of the item selected by the user
If no item is selected, the value is set to -1 (an
invalid index value)
Can use SelectIndex to determine if an item has
been selected by comparing to -1
Example:
Slide 5- 16
ListBox SelectedItem Property
Instead of using the SelectedIndex property as
follows:
If lstMonths.SelectedIndex <> -1 Then
month = lstMonths.Items(lstMonths.SelectedIndex)
End If
Slide 5- 17
ListBox Sorted Property
Sorted is a boolean property
When set to true, values in the Items property are
displayed in alphabetical order
When set to false, values in the Items property
are displayed in the order they were added
Eg
lstStudents.Sorted = True
Slide 5- 18
ListBox Items.Add Method
Items can be added to the end of a ListBox list in
your VB code using the Add method
Format is
ListBox.Items.Add(Item)
ListBox is the name of the control
Item is a string value to add to the Items property
Example:
lstStudents.Items.Add(“Mary")
Slide 5- 19
ListBox Items.Insert Method
Items can be added at a specific position of a
ListBox in VB code using the Insert method
ListBox.Items.Insert(Index, Item)
Index specifies position where Item is placed
Index is zero based similar to SelectedIndex
property
Items that follow are “pushed” down
Example inserting "Jean“ as the 3rd item
lstStudents.Items.Insert(2, "Jean")
Slide 5- 20
ListBox Methods to Remove Items
ListBox.Items.RemoveAt(Index)
Removes item at the specified index
ListBox.Items.Remove(Item)
Removes item with value specified by Item
ListBox.Items.Clear()
Removes all items in the Items property
Examples:
lstStudents.Items.RemoveAt(2) ‘remove 3rd item
lstStudents.Items.Remove(“Jean”) ‘remove item Jean
lstStudents.Items.Clear() ‘remove all items
Slide 5- 21
3. Repetition Structure (or Loop)
Visual Basic has three structures that allow a
statement or group of statements to repeat
Do While
Do Until
For...Next
Slide 5- 22
3.1 The Do While Loop
Do While Flowchart
The Do While loop
If the expression is
true, the statement(s)
are executed
Expression is then True
Expression statement(s)
evaluated again
As long as the False
expression remains
true, the statement(s)
continue to be repeated
Slide 5- 24
Do While Syntax
Do, While, and Loop are new keywords
The Do While statement marks the beginning of
the loop
The Loop statement marks the end
The statements to repeat are found between
these and called the body of the loop
Do While expression
statement(s)
Loop
Slide 5- 25
Do While Example 1
Slide 5- 27
Infinite Loops
A loop must have some way to end itself
Something within the body of the loop must
eventually force the test expression to false
In the previous example
The loop continues to repeat
Slide 5- 28
Counters
Variables called counters are frequently used to
control Do While loops
intCount in previous example is a counter
Counters generally initialized before loop begins
Dim intCount As Integer = 0
Counter must be modified in body of loop
intCount += 1
The test expression ends the loop when the
counter compares to some value
Slide 5- 29
Pretest vs. Posttest Loops
Previous Do While loops are in pretest form
Expression is tested before the body of the
loop is executed
The body may not be executed at all
Do
statement(s)
Loop While expression statement(s)
False
Slide 5- 31
A Posttest Running Total Loop
Dim num, sum As Integer
sum = 0
Do
sum = sum + num
lstOutput.Items.Add(num & vbTab & sum)
num = num + 1
Slide 5- 32
3.2 The Do Until loop
A Do Until loop
Repeats as long as its test expression is false
Slide 5- 34
Do Until: Pretest & Posttest Forms
Pretest:
Do Until expression
statement(s)
Loop
Posttest:
Do
statement(s)
Loop Until expression
Slide 5- 35
Do Until Loop – (Prints 10 t0 1 )
Public Class Form1
Do Until Intcount = 1
ListBox1.Items.Add(Intcount)
Intcount -= 1
Loop
End Sub
End Class
Slide 5- 36
3.3 For…Next Loop
The For...Next Loop Is Designed to
Use a Counter Variable and Iterates a
Specific Number of Times
Slide 5- 37
For…Next Loop
Ideal for loops that require a counter
For CounterVariable = StartValue To EndValue [Step]
statement
Next [CounterVariable]
For, To, and Next are keywords
CounterVariable tracks number of iterations
StartValue is initial value of counter
EndValue is counter number of final iteration
Optional Step allows the counter to increment at
a value other than 1 at each iteration of the loop
Slide 5- 38
For…Next Flowchart
set
counter
to StartValue
True
Slide 5- 39
For…Next Example 1
The following code uses a For…Next loop to
print on listbox numbers 0 to 20
Public Class Form1
Private Sub btnShow_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnShow.Click
Dim i As Integer
For i = 0 To 20
ListBox1.Items.Add(i)
Next
End Sub
End Class
Slide 5- 40
More on the StepValue
It’s optional and if not specified, defaults to 1
The following loop iterates 11 times with counter
values 0, 10, 20, …, 80, 90, 100
For x = 0 To 100 Step 10
MessageBox.Show("x is now " & x.ToString)
Next x
Slide 5- 42
Exiting a Loop Prematurely
In some cases it is convenient to end a loop
before the test condition would end it
The following statements accomplish this
Exit Do (used in Do While or Until loops)
Slide 5- 43
Example: Exit a Loop Prematurely
Slide 5- 44
When to Use the Do While Loop
Use Do While when the loop should repeat as
long as the test expression is true
Can be written as a pretest or posttest loop
A pretest Do While is ideal when the body should
not be perfomed for a test expression that is
initially false
Posttest loops are ideal when you always want
the loop to iterate at least once
Slide 5- 45
When to Use the Do Until Loop
Use Do Until when the loop should repeat as long
as the test expression is false
Can be written as a pretest or posttest loop
A pretest Do Until is ideal when the body should
not be perfomed for a test expression that is
initially true
Posttest loops are ideal when you always want
the loop to iterate at least once
Slide 5- 46
When to Use the For Next Loop
The For...Next loop is a pretest loop ideal when a
counter is needed
It automatically increments the counter variable at
the end of each iteration
The loop repeats as long as the counter variable
is not greater than an end value
Used primarily when the number of required
iterations is known
Slide 5- 47
Nested Loops
3.4
A Loop that is Inside Another
Loop is Called a Nested Loop
Nested Loops
The body of a loop can contain any type of VB
statements including another loop
When a loop is found within the body of another
loop, it’s called a nested loop
Slide 5- 49
Nested Loop Example
Sub Main()
Dim i, j As Integer
For i = 1 To 5
For j = 1 To i
Console.Write(i)
Next
Console.WriteLine()
Next
Console.ReadLine()
End Sub
Slide 5- 50