Presentation is loading. Please wait.

Presentation is loading. Please wait.

IS 350 Loops.

Similar presentations


Presentation on theme: "IS 350 Loops."— Presentation transcript:

1 IS 350 Loops

2 Objectives Write Do loops and For loops to execute statements repeatedly Use generic collections of objects to create a list; locate items in a list; and add, edit, and delete list items Use controls that operate on lists, including the ListBox and ComboBox controls Use the DataGridView control and loops to work with tabular 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 the file Accounting problems – depreciation and loan balances are calculated repeatedly for multiple periods

5 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

6 Do While and Do Until Loops (syntax)
Do While and Do Until loops execute statements repeatedly Do [While | Until] condition [statements] [Continue] [Exit Do] Loop statements

7 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 Continue statement executes the loop’s condition The Exit Do statement causes the Do loop to exit immediately statements following the loop execute

8 Execution flow of a Do Until loop

9 Execution flow of a Do While loop

10 Loops and Counters A counter is a variable whose value increases by constant value each time through a loop The constant value is typically 1 A counter takes the following general form: Counter = Counter + 1 Counter += 1

11 Loops and Counters (example 1)
Print the counting numbers from 1 through 10 using a Do Until loop Dim Counter As Integer = 1 Do Until Counter > 10 Console.WriteLine(Counter) Counter = Counter + 1 Loop

12 Loops and Counters (example 2)
Print the counting numbers from 1 through 10 using a Do While loop Dim Counter As Integer = 1 Do While Counter <= 10 Console.WriteLine(Counter) Counter += 1 Loop

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

14 Post-Test Do Loops (syntax 2)
The statement(s) in the loop execute first, and then the condition is tested 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 becomes True

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

16 Execution flow of a posttest Do loop

17 The Role of an Accumulator
An accumulator is similar to a counter An accumulator’s value 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 Console.WriteLine(Counter.ToString()) Console.WriteLine(Accumulator.ToString()) 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 infinite loops Infinite loop example (Counter is always equal to 1): Dim Counter As Integer = 1 Do While Counter < 10 Console.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 1) For counter = start To end [Step increment]
[statements] [Continue] [Exit For] 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 Step increment clause

26 For Loops (example) Print the counting numbers from 1 to 10
Dim Counter As Integer For Counter = 1 To 10 Console.WriteLine(Counter) Next Counter

27 Execution path 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 Console.Write(Result.ToString("d3") _ & " ") Next Console.WriteLine("")

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 = 2100 To 2000 Step –5 Console.WriteLine(CurrentYear.ToString) Next CurrentYear

30 The Implications of Long-running Loops
Some loops can run for hours Display messages periodically in long-running loops Improve the performance of long-running loops where possible Move unnecessary statements outside of a loop

31 For Loop Errors Do not increment a loop’s counter
The following statements: For Counter = 1 To 10 Counter += 1 Console.Write(Counter & " ") Next Produce the following output:

32 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’s possible to create custom collections

33 Members of Collections
Add method adds an item to the end of a collection Count property returns the number of items in a collection Item property references an item in a collection The property is 0-based RemoveAt method removes a collection item The method is also 0-based

34 Categories of Collections
One category of collection can store items having 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 collection A third category of collection stores items having the same data type

35 Creating a List The List class is used to create collections that store items having the same data type This type of a collection is called a generic list Example to declare a list of type Employee Private EmployeeList As New _ List(Of Employee)

36 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

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

38 Memory allocation using the List class

39 Common List Errors It's possible to add references to the same object to a list This situation is commonly an error but may be the desired outcome

40 Incorrect list references

41 Referencing a List Item (example)
The Item property references a list item Argument contains the 0-based index value Reference the first Employee in the list named EmployeeList Dim EmpCurrent As Employee EmpCurrent = EmployeeList.Item(0) Console.WriteLine(EmpCurrent.EmployeeID.ToString) Console.WriteLine(EmpCurrent.EmployeeName)

42 Updating a Collection Item
A collection item can be updated in two ways Replace the data stored in an existing item Replace an item entirely Replace one class instance with another

43 Updating list items

44 Replacing list items

45 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.", _ "Error", MessageBoxbuttons.OK, _ MessageBoxIcon.Error) End Try

46 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

47 Enumerating a Collection with a For loop
A Do loop or For loop can be used to enumerate the items in a collection Enumerate from 0 to Count – 1 A For Each loop can also be used to enumerate the items in a collection A For Each loop is preferable because of its simplified syntax

48 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.Item(Index) Console.WriteLine( _ EmpCurrent.EmployeeID.ToString()) Console.WriteLine(EmpCurrent.EmployeeName) Next

49 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

50 The For Each Loop (syntax)
For Each object In group [statements] [Exit For] Next statements

51 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

52 The For Each Loop (example)
Enumerate the EmployeeList Dim EmpCurrent As Employee For Each EmpCurrent In EmployeeList Console.WriteLine( _ EmpCurrent.EmployeeID.ToString()) Console.WriteLine( _ EmpCurrent.EmployeeName) Next

53 Introduction to Predefined Collections
Visual Studio supports many predefined collections The Controls collection apples to a Form or container control It references the control instances contained by the form or container control instance Each object in the collection has a data type of Control

54 The Controls Collection (example)
Enumerate the Controls collection Dim CurrentControl As Control For Each CurrentControl In _ Me.Controls ' Statements to reference the ' current control instance. Next

55 The TypeOf Statement (syntax)
The Type Of statement tests the data type of an object result = TypeOf objectExpression Is typeName result contains the Boolean result of testing the object's type result is True if objectExpression is of typeName objectExpression contains an instance of a reference type typeName contains the data type

56 The TypeOf Statement (example)
Determine if the current control instance is a TextBox Dim CurrentControl As Control For Each CurrentControl In Me.Controls If TypeOf CurrentControl Is TextBox Then ' Statements to work with the ' current TextBox control instance. End If Next

57 Introduction to Controls Involving Loops
Three controls are discussed in this chapter that use loops The ComboBox and ListBox controls display lists of data and derive from the System.Windows.Forms.ListControl class The DataGridView control displays a 2-dimensional grid

58 Hierarchical organization of the ComboBox and ListBox controls

59 The System.Windows. Forms.ListControl class
Items property is a collection Each object is an item in the list SelectedIndex property contains the 0-based index value of the selected item The value is -1 if no item is selected SelectedItem property contains a reference to the selected item itself The value is Nothing if no item is selected ClearSelection method deselects all selected items Windows fires the SelectedIndexChanged event when an item is selected

60 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

61 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 end user can select one item or many items

62 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

63 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 = 1 To 20 lstDemo.Items.Add("Item " & _ Count.ToString()) Next

64 String Collection Editor dialog box

65 Working with the Selected List Item
When the end user selects an item, a SelectedIndexChanged event fires Two properties are of interest The SelectedItem property references the object currently selected The SelectedIndex property stores the 0-based index of the currently selected item

66 Working with the Selected Item (example)
Display information about the selected item Private Sub _ cboSingleSelect_SelectedIndexChanged( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles _ cboSingleSelect.SelectedIndexChanged lblSelectedComboBoxItem.Text = _ cboSingleSelect.SelectedItem.ToString() lblSelectedComboBoxIndex.Text = _ cboSingleSelect.SelectedIndex.ToString() End Sub

67 Selecting an Item Programmatically (examples)
Select the first item in the combo box named cboSingleSelect cboSingleSelect.SelectedIndex = 0 Clear the selected item cboSingleSelect.SelectedIndex = -1

68 Introduction to the DataGridView Control
The DataGridView control displays data as a 2-dimensional grid made up of rows and columns The intersection of a row and column is called a cell It can operate in two modes The DataGridView can be bound to a data source It can operate in an unbound mode Rows and columns are added manually

69 DataGridView Control instance displaying a multiplication table

70 Working with the DataGridView Control
Steps to populate the grid Add the columns Add the rows The columns must be added before the rows are added Populate the cells It's possible to delete existing rows

71 Adding Columns to the DataGridView
The Add method of the Columns collection adds a column as follows: dgvDemo.Columns.Add("Column1", _ "VisibleText") The first argument contains the column name The second argument contains the column's caption Columns are added to the end of the list

72 Adding Rows to the DataGridView
Without arguments, the Add method adds one row dgvDemo.Rows.Add() The Add method will add multiple rows when called with an Integer argument dgvDemo.Rows.Add(20)

73 Referencing and Populating Individual Grid Cells
The following statements reference the first cell in the first row: Dim CurrentCell As DataGridViewCell CurrentCell = dgvDemo.Rows(0).Cells(0) dgvDemo.Rows(0) references the first row in the collection Cells(0) references the first cell in the first row The data type of a cell is DataGridViewCell

74 Storing and Retrieving Cell Values
The Value property of the DataGridViewCell stores the cell's value Example: CurrentCell.Value = “Mary Deems” txtDemo.Text = _ CurrentCell.Value.ToString()

75 Deleting Rows from the DataGridView
Like most collections, the RemoveAt method removes a row The argument contains the 0-based index value Example to remove the first row dgvDemo.Rows.RemoveAt(0)

76 Using a Loop to Examine Cells
The Rows collection has a Count property containing the number of elements (rows) Thus, a For loop can be used to examine each row Examine the first column (cell) in each row Dim ColumnTotal As Double = 0 Dim CurrentRow As Integer For CurrentRow = 0 To dgvDemo.Rows.Count – 1 ColumnTotal += _ dgvDemo.Rows(CurrentRow).Cells(0).Value Next

77 Chapter Summary Loops are used to execute statements repeatedly
Loops contain a condition that evaluates to a Boolean value Loops are of two types Do Loops For loops Lists store objects having the same or similar data types Use the Add method to add a list item Use the Item property to reference or update a list item Use the RemoveAt method to remove an item

78 Chapter Summary (continued)
The Controls collection references the control instances on a form or container control Use the TypeOf operator to determine the data type The ComboBox and ListBox controls display a list of items The DataGridView stores tabular data made up of rows and columns The intersection of a row and column is called a cell


Download ppt "IS 350 Loops."

Similar presentations


Ads by Google