chapter 8 using repetition with loops and lists. class 8: loops and lists write do loops to execute...

49
Chapter 8 Using Repetition with Loops and Lists

Upload: violet-harvey

Post on 24-Dec-2015

257 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Chapter 8

Using Repetition with Loops and Lists

Page 2: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Class 8: Loops and Lists

• Write Do loops to execute statements repeatedly

• Write For loops to execute statements repeatedly

• Use generic collections of objects to locate items in a list and to add, change, and delete list items

• Use controls that operate on lists, including the ListBox and ComboBox controls

• Use the DataGridView control to work with tabular data

Page 3: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Introduction to Loops

• Chapter 7 discussed the decision-making structure• This chapter discusses the repetition structure• After completing this chapter, you will know

about the three primary control structures– The sequence structure

– The decision-making structure

– The repetition structure

• These structures are part of nearly every program written

Page 4: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Executing Statements Repeatedly

• Situations where repetition is used– Calculating payroll – a loop is used to calculate

the payroll for each employee– Reading multiple records in a file – a loop is

used to process each record in a file– Graphical animations – a loop is used to move

graphical objects about the screen– Accounting problems – depreciation and loan

balances are calculated repeatedly for multiple periods

Page 5: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Do While and Do Until Loops (Syntax)

• Do While and Do Until loops execute statements repeatedlyDo [While | Until] condition

[statements]

[Exit Do]

[statements]

Loop

statements

Page 6: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Do While and Do Until Loops (Syntax, continued)

• Do While and Do Until loops test the condition before executing the statements in a loop– The condition evaluates to a Boolean value

• The Do While form executes statements while the condition is True

• The Do Until form executes statements until the condition becomes True

• The Exit Do statement causes the Do loop to exit immediately– statements following the loop execute

Page 7: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Figure 8-1: Execution Flow of a Do Until Loop

Page 8: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Figure 8-2: Execution Flow of a Do While Loop

Page 9: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Loops and Counters

• A counter is a variable whose value increases by a constant value each time through a loop– The constant value used to increment the

counter is typically 1

• A counter takes the following general form:– Counter = Counter + 1– Counter += 1

Page 10: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Loops and Counters (Example)

• Print the counting numbers 1 through 10 using a Do Until loop

Dim Counter As Integer = 1

Do Until Counter > 10

Debug.WriteLine(Counter)

Counter += 1

Loop

Page 11: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Loops and Counters (Example, continued)

• Print the counting numbers 1 through 10 using a Do While loop

Dim Counter As Integer = 1

Do While Counter <= 10

Debug.WriteLine(Counter)

Counter += 1

Loop

Page 12: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Types of Loops

• Pre-test loops test a condition before executing the statements in a loop

• Post-test loops execute the loop's statements first, and then test the loop's condition

Page 13: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Post-Test Do Loops (Syntax)

• In a post-test loop, the condition is tested after the loop statements have executedDo

[statements]

[Exit Do]

[statements]

Loop [While | Until] condition

statements

Page 14: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Post-Test Do Loops (Syntax, continued)

• Note the statement(s) in the loop are first executed, and then the condition is tested– Thus, the loop's statements will always execute at least

once

• The Do Loop While variation executes the loop's statements while a condition is True

• The Do Loop Until variation executes the loop's statements until a condition is True

Page 15: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Post-Test Do Loops (Example)

• Print the counting numbers 1 through 10Dim Counter As Integer = 1

Do

Debug.WriteLine(Counter)

Counter += 1

Loop While Counter < 10

Page 16: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Figure 8-3:Execution Flow of a Post-test Do Loop

Page 17: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

The Role of an Accumulator

• An accumulator is similar to a counter– An accumulator is updated each time the statements

in a loop execute– An accumulator is used to calculate (accumulate) a

total

• An accumulator takes the following general form:– Accumulator = Accumulator + value– Accumulator += value

Page 18: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Accumulator (Example)

• Store the sum of the counting numbers 1 through 10

Dim Counter As Integer = 1

Dim Accumulator As Integer = 0

Do While Counter <= 10

Debug.Write (Counter)

Debug.WriteLine(“ “ & Accumulator)

Accumulator += Counter

Counter += 1

Loop

Page 19: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Accumulator (Example) (continued)

Page 20: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Infinite Loops

• A condition must ultimately occur causing a loop to exit

• Loops can be mistakenly written so that statements execute indefinitely – These loops are called infinite loops

• Infinite loop example (Counter is always equal to 1):Dim Counter As Integer = 1

Do While Counter < 10

Debug.WriteLine(Counter)

Loop

Page 21: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Nested Do Loops and Decision-making

• Loops can be nested, just as decision-making statements can be nested

• Loops can contain decision-making statements

• Decision-making statements can contain loops

• Both can contain nested sequence structures

Page 22: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Combining Looping and Decision-making Statements

(Example)• Determine whether a number is prime

Private Shared Function IsPrime( _ ByVal arg As Integer) As Boolean

Dim Count As Integer = 2 Do While Count < arg If (arg Mod Count) = 0 Then Return False End If Count += 1 Loop Return True

End Function

Page 23: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

For Loops (Introduction)

• For loops execute statements repeatedly

• Use a For loop in place of a Do loop when the iteration count (the number of times the loop will execute) is known in advance

• For loops run more quickly than comparable Do loops

• For loops are more readable than equivalent Do loops

Page 24: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

For Loops (Syntax)

For counter = start To end [Step increment]

[statements]

[Exit For]

[statements]

Next [counter]

statements

Page 25: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

For Loops (Syntax, continued)

• The For and Next statements mark the beginning and end of a For loop

• counter is first initialized to start– The value of counter is incremented automatically

– Do not explicitly set the value of counter

• By default, counter is incremented by one each time through the loop– This value can be changed by including the Step

increment clause

Page 26: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

For Loops (Example)

• Print the counting numbers 1 to 10Dim Counter As Integer

For Counter = 1 To 10

Debug.WriteLine(Counter)

Next Counter

Page 27: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Figure 8-5: Execution of a For Loop

Page 28: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Nested For Loop (Example)

• Print a multiplication tableDim Factor1, Factor2, Result As Integer

For Factor1 = 1 To 10

For Factor2 = 1 To 10

Result = Factor1 * Factor2

Debug.Write(Result.ToString() & " ")

Next

Debug.WriteLine("")

Next

Page 29: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Using the Step Keyword

• Use the Step keyword to modify a counter's value by a value other than 1

• Example to decrement a counter by 5

Dim CurrentYear As Integer

For CurrentYear = 2000 To 1900 Step –5

Debug.WriteLine(CurrentYear.ToString)

Next CurrentYear

Page 30: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Introduction to Collections

• Collections store repeating items as a list

• All collections store references to objects having the same data type or different data types

• Some collections are predefined– The Controls collection, for example

• It is possible to create custom collections

Page 31: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Members of Collections

• The Add method adds an item to the end of a collection

• The Count property returns the number of items in a collection

• The Item method references an item in a collection– The method is 0-based

• The RemoveAt method removes a collection item– The method is also 0-based

Page 32: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Categories of Collections

• One category of collection can store items with different data types

• A second category of collection requires the data type of all items be the same– This type of collection is called a generic list

• A third category of collection stores items always having the same data type

Page 33: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Creating a List

• The List class is used to create collections that store items with the same data type– This type of a collection is called a generic list– The List class is new to Visual Studio 2005

• Example to declare a list of type Employee:Private EmployeeList As New _ List(Of Employee)

Page 34: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Adding Items to a List

• An instance of the List class is empty when first created– There are no items in the list

• Calling the Add method adds an item to the end of the list– The Add method accepts one argument – the item

to add– The item added must have the same data type as the

data type expected by the list

Page 35: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Adding Items to a List (Example)

• Add two items to a list

Dim EmpCurrent As New Employee

EmpCurrent.EmployeeID = 18223

EmpCurrent.EmployeeName = "Joe Smith"

EmployeeList.Add(EmpCurrent)

EmpCurrent = New Employee

EmpCurrent.EmployeeID = 24428

EmpCurrent.EmployeeName = "Mary Deems"

EmployeeList.Add(EmpCurrent)

Page 36: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Referencing a List Item (Example)

• The Item method is used to reference a list item

• Reference the first Employee in the list named EmployeeListDim EmpCurrent As Employee

EmpCurrent = EmployeeList.Item(0)

Debug.WriteLine(EmpCurrent.EmployeeID.ToString)

Debug.WriteLine(EmpCurrent.EmployeeName)

Page 37: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Deleting a Collection Item

• Call the RemoveAt method with one argument – the 0-based index of the item to remove– An exception will be thrown if the index value is

invalid• Example to remove the first collection item:

Try EmployeeList.RemoveAt(0)Catch ex As ArgumentOutOfRangeException MessageBox.Show("Employee not found.")End Try

Page 38: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Determining the Size and Capacity of a Collection

• The Count property stores the number of items in a collection

• The Capacity property stores the number of items the collection can store– The initial value for the Capacity property is 4

– The value doubles, as necessary, as Count reaches Capacity

• This is done for performance reasons

Page 39: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Enumerating a Collection with a For loop

• A Do loop or For loop can be used to enumerate the items in a collection

• A For loop is preferable– Enumerate from 0 to Count - 1

• A For Each loop can also be used to enumerate the items in a collection

Page 40: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Enumerating a Collection with a For Loop (Example)

• Enumerate the EmployeeList collectionDim Index As Integer

Dim EmpCurrent As Employee

For Index = 0 To EmployeeList.Count – 1

EmpCurrent = EmployeeList(Index)

Debug.WriteLine( _

EmpCurrent.EmployeeID.ToString)

Debug.WriteLine(EmpCurrent.EmployeeName)

Next

Page 41: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Introduction to the For Each Loop

• The For Each loop is used to enumerate collections

• Conceptually, it works the same way as a For loop– Each time through the loop, an object is

returned from the collection

Page 42: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

The For Each Loop (Syntax)

For Each object In group

[statements]

[Exit For]

[statements]

Next

statements

Page 43: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

The For Each Loop (Syntax, continued)

• object contains an object reference

• group contains the collection

• Each time through the For Each loop an object is returned

Page 44: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

The For Each Loop (Example)

• Enumerate the EmployeeListDim EmpCurrent As Employee

For Each EmpCurrent In EmployeeList

Debug.WriteLine( _ EmpCurrent.EmployeeID.ToString)

Debug.WriteLine( _

EmpCurrent.EmployeeName.ToString)

Next

Page 45: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Introduction to the ComboBox Control

• The ComboBox control displays a list of items from which the end user selects one item

• The DropDownStyle property defines the visual appearance of the ComboBox– DropDown– Simple– DropDownList

Page 46: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Introduction to the ListBox Control

• The ListBox control is similar to the ComboBox control– The visible region does not drop down

• The SelectedItems property returns a collection of the selected items

• The SelectionMode property defines whether the user can select one item or many items

• The ClearSelected method clears the selected items

Page 47: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Working with the ComboBox and ListBox Controls

• Common operations– Items must be added to the list– Conditional actions must be performed as the

end user selects list items– Items must be selected programmatically

Page 48: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Adding Items to a ComboBox or ListBox

• Items can be added at design time using the String Collection Editor

• Items can be added at run time by calling the Add method as follows:

For Count = 0 To 6

lstDemo.Items.Add("Item " & _

Count.ToString)

Next

Page 49: Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements

Figure 8-13: The String Collection Editor Dialog Box