IS 350 Loops.

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Programming with Microsoft Visual Basic 2008 Fourth Edition
Programming with Microsoft Visual Basic th Edition
Microsoft Visual Basic: Reloaded Chapter Seven More on the Repetition Structure.
Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.
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.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
1 Chapter 6 – Repetition 6.1 Do Loops 6.2 For...Next Loops 6.3 List Boxes and Loops.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
Chapter 12: How Long Can This Go On?
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Seven More on the Repetition Structure.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
5-1 Chapter 5 The Repetition Process in VB.NET. 5-2 Learning Objectives Understand the importance of the repetition process in programming. Describe the.
1 Week 6 The Repetition Structure. 2 The Repetition Structure (Looping) Lesson A Objectives After completing this lesson, you will be able to:  Code.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 8: Chapter 5: Slide 1 Unit 8 List Boxes and the Do While Looping Structure.
Chapter 6: The Repetition Structure
Tutorial 6 The Repetition Structure
Microsoft Visual Basic 2008: Reloaded Third Edition Chapter Six The Do Loop and List Boxes.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Chapter 6 - VB.Net by Schneider1 Chapter 6 – Repetition 6.1 Do Loops 6.2 Processing Lists of Data with Do Loops Peek Method Counters and Accumulators Flags.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 5A Repetition (Concepts)
Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.
Chapter 6 - VB 2005 by Schneider1 Chapter 6 – Repetition 6.1 Do Loops 6.2 Processing Lists of Data with Do Loops 6.3 For...Next Loops 6.4 A Case Study:
Iterations (aka Loops). 2 Loops Loops (iterations) are segments of code that may be executed several times. Fixed-count (definite) loops repeat a fixed.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 13 How Long Can This Go On?
Unit 6 Repetition Processing Instructor: Brent Presley.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Iterations (aka Loops). 2 Loops Loops (iterations) are segments of code (loop body) that may be executed several times. Fixed-count (definite) loops repeat.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 Chapter 6 – Repetition 6.1 Do Loops 6.2 Processing Lists of Data with Do Loops 6.3 For...Next Loops 6.4 A Case Study: Analyze a Loan.
COMPUTER PROGRAMMING I Apply Procedures to Develop List Box and Combo Box Objects.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.-Edited By Maysoon Al-Duwais1.
Visual Basic Fundamental Concepts
Programming in visual basic .net Visual Basic Building Blocks
UNIT 5 Lesson 15 Looping.
Apply Procedures to Develop Menus, List Box and Combo Box Objects
REPETITION CONTROL STRUCTURE
IS 350 Application Structure
IS 350 Arrays.
Chapter 5- Control Structures: Part 2
Topics Introduction to Repetition Structures
Loop Structures.
Lists, Loops, Validation, and More
Chapter 5: Repetition Structures
Topics Introduction to Repetition Structures
Using Procedures and Exception Handling
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Chapter 5 – Control Structures: Part 2
Repeating Program Instructions
Chapter 6 – Repetition 6.1 Do Loops 6.2 For...Next Loops
Arrays, For loop While loop Do while loop
Visual Basic..
Microsoft Visual Basic 2005: Reloaded Second Edition
Topics Introduction to File Input and Output
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
CIS 16 Application Development Programming with Visual Basic
Chapter 6 Control Statements: Part 2
Introduction to Problem Solving and Control Statements
Lecture Set 10 Windows Controls and Forms
Chapter 6 - VB.Net by Schneider
Programming Logic and Design Fifth Edition, Comprehensive
Topics Introduction to Repetition Structures
Topics Introduction to File Input and Output
Lecture Set 9 Arrays, Collections, and Repetition
Presentation transcript:

IS 350 Loops

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

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

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

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

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

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

Execution flow of a Do Until loop

Execution flow of a Do While loop

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

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

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

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

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

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

Execution flow of a posttest Do loop

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

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

Accumulator (example continued)

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

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

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

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

For Loops (syntax 1) For counter = start To end [Step increment] [statements] [Continue] [Exit For] Next [counter] 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

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

Execution path of a For loop

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("")

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

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

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: 2 4 6 8 10

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

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

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

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)

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

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"

Memory allocation using the List class

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

Incorrect list references

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)

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

Updating list items

Replacing list items

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

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

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

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

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

The For Each Loop (syntax) For Each object In group [statements] [Exit For] Next 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

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

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

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

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

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

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

Hierarchical organization of the ComboBox and ListBox controls

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

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

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

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

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

String Collection Editor dialog box

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

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

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

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

DataGridView Control instance displaying a multiplication table

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

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

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)

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

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()

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)

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

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

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