0% found this document useful (0 votes)
17 views

JK VB NET 6 Repetition Structures Loops

JK VB NET 6 Repetition Structures Loops

Uploaded by

curtisandrea242
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

JK VB NET 6 Repetition Structures Loops

JK VB NET 6 Repetition Structures Loops

Uploaded by

curtisandrea242
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

• 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

 Write a program that will print out the following


pattern on the screen

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

 It also discusses the use of


 List Boxes

 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])

 Prompt - message to the user (required)


 Title - text for the box's title bar
 Default - default text for user's input
 Xpos - X coordinate for the box's position
 Ypos - Y coordinate for the box's position
 Square brackets around Title and following
arguments indicate these are optional

Slide 5- 7
Sample InputBox Usage
strUserInput = InputBox("Enter the distance.", _
"Provide a Value", "150")

 If the users clicks OK without entering a value, 150 will be


assigned to strUserInput due to the default value

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

 View properties & click the Items ellipsis button

 This property is a collection, a list of values

 Type each value on a separate line

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

 The number of entries in the list can be assigned


to an integer variable
numEmployees = lstEmployees.Items.Count

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

 The second item has an index of 1, etc.

 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:

If lstLocations.SelectedIndex <> -1 Then


location = lstLocations.Items(lstLocations.SelectedIndex)
End If

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

 The SelectedItem property can be used to


retrieve the value of a selected item as follows:
If lstMonths.SelectedIndex <> -1 Then
month = lstMonths.SelectedItem.ToString)
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

Private Sub btnRunDemo_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles btnRunDemo.Click
' Demonstrate the Do While loop
Dim intCount As Integer = 0

Do While intCount < 10


lstOutput.Items.Add("Hello")
intCount += 1
Loop
End Sub

Note that programming style


dictates the body of the
loop be indented for clarity
Slide 5- 26
Do While Example 2
Dim num, sum As Integer
sum = 0

Do While num < 10


sum = sum + num
lstOutput.Items.Add(num & vbTab & sum)
num = num + 1
Loop

The above example will list numbers on a listbox


(lstOutput) while num <10. it will also calculate the
sum of these numbers.

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

 intCount increases by one for each repetition

 Finally intCount is not <10 and the loop ends

 If the test expression can never be false, the loop


will continue to repeat forever
 This is called an infinite loop

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 While loops also have a posttest form


 The body of the loop is executed first

 Then the expression is evaluated

 Body repeats as long as expression is true

 A posttest loop always executes the body

of the loop at least once


Slide 5- 30
Posttest Loop Syntax and Flowchart

Do
statement(s)
Loop While expression statement(s)

 The statement(s) must


be executed at least
once, irrespective of True
the expression used Expression

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

Loop While num < 10

Slide 5- 32
3.2 The Do Until loop

A Do Until Loop Iterates Until Its Test


Expression Is True
Do Until vs. Do While
 A Do While loop
 Repeats as long as its test expression is true

 Ends when its test expression becomes false

 A Do Until loop
 Repeats as long as its test expression is false

 Ends when its test expression becomes true

 The Do Until loop has a pretest and posttest


form just as a Do While loop

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

 Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnShow.Click

 Dim Intcount As Integer


 Intcount = 10

 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

Counter = False increment


EndValue?
statement(s) counter

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

 StepValue may be negative, causing the loop to


count downward
For x = 10 To 1 Step -1
MessageBox.Show("x is now " & x.ToString)
Next x
Slide 5- 41
For…Next Example 1(Class Exercise )
 Write a program that makes use of the For …
Next loop to add to a listBox all the ODD
Numbers between 31 and 50

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)

 Exit For (used in For Next loops)

 Use this capability with caution


 It bypasses normal loop termination

 Makes code more difficult to debug

Slide 5- 43
Example: Exit a Loop Prematurely

maxNumbers = CInt(InputBox("How many numbers do " & _


"you wish to sum?"))
total = 0
For x = 1 to maxNumbers
input = InputBox("Enter a number.")
If input = "" Then
Exit For
Else
num = CDbl(input)
total += num
End If
Next x
MessageBox.Show(“Sum of the numbers is " & total.ToString)

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

You might also like