1 / 49

Chapter 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 repeatedly Use generic collections of objects to locate items in a list and to add, change, and delete list items

nira
Download Presentation

Chapter 8

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 8 Using Repetition with Loops and Lists

  2. 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 withtabular data

  3. 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

  4. 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

  5. DoWhile and DoUntil Loops (Syntax) • Do While and DoUntil loops execute statements repeatedly Do [While | Until] condition [statements] [Exit Do] [statements] Loop statements

  6. DoWhile and DoUntil Loops (Syntax, continued) • DoWhile and DoUntil loops test the condition before executing the statements in a loop • The condition evaluates to a Boolean value • The DoWhile form executes statements while the condition is True • The DoUntil form executes statements until the condition becomes True • The Exit Do statement causes the Do loop to exit immediately • statements following the loop execute

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

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

  9. 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

  10. 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

  11. 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

  12. 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

  13. Post-Test Do Loops (Syntax) • In a post-test loop, the condition is tested after the loop statements have executed Do [statements] [Exit Do] [statements] Loop [While | Until] condition statements

  14. 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 DoLoopWhile variation executes the loop's statements while a condition is True • The DoLoopUntil variation executes the loop's statements until a condition is True

  15. Post-Test Do Loops (Example) • Print the counting numbers 1 through 10 Dim Counter As Integer = 1 Do Debug.WriteLine(Counter) Counter += 1 Loop While Counter < 10

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

  17. 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

  18. 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

  19. Accumulator (Example) (continued)

  20. 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 infiniteloops • Infinite loop example (Counter is always equal to 1): Dim Counter As Integer = 1 Do While Counter < 10 Debug.WriteLine(Counter) Loop

  21. 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

  22. 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

  23. 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

  24. For Loops (Syntax) For counter = start To end [Step increment] [statements] [Exit For] [statements] Next [counter] statements

  25. 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 Stepincrement clause

  26. For Loops (Example) • Print the counting numbers 1 to 10 Dim Counter As Integer For Counter = 1 To 10 Debug.WriteLine(Counter) Next Counter

  27. Figure 8-5: Execution of a For Loop

  28. Nested For Loop (Example) • Print a multiplication table Dim 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

  29. 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

  30. 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

  31. 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

  32. 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

  33. 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)

  34. 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

  35. 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)

  36. Referencing a List Item (Example) • The Item method is used to reference a list item • Reference the first Employee in the list named EmployeeList Dim EmpCurrent As Employee EmpCurrent = EmployeeList.Item(0) Debug.WriteLine(EmpCurrent.EmployeeID.ToString) Debug.WriteLine(EmpCurrent.EmployeeName)

  37. 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

  38. 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

  39. 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 ForEach loop can also be used to enumerate the items in a collection

  40. Enumerating a Collection with a For Loop (Example) • Enumerate the EmployeeList collection Dim 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

  41. Introduction to the ForEach Loop • The ForEach 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

  42. The ForEachLoop (Syntax) For Each object In group [statements] [Exit For] [statements] Next statements

  43. The For Each Loop (Syntax, continued) • object contains an object reference • group contains the collection • Each time through the ForEach loop an object is returned

  44. The ForEach Loop (Example) • Enumerate the EmployeeList Dim EmpCurrent As Employee For Each EmpCurrent In EmployeeList Debug.WriteLine( _ EmpCurrent.EmployeeID.ToString) Debug.WriteLine( _ EmpCurrent.EmployeeName.ToString) Next

  45. 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

  46. 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

  47. Working with the ComboBoxand 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

  48. Adding Items to a ComboBoxor 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

  49. Figure 8-13: The String Collection Editor Dialog Box

More Related