Programming with Microsoft Visual Basic 2017 Chapter 5

Programming with Microsoft Visual Basic 2017 Chapter 5 The Repetition Structure

FOCUS ON THE CONCEPTS LESSON Concepts covered in this lesson: • Repetition structures • Do…Loop statement (pretest loop) • Do…Loop statement (posttest loop) • String concatenation • Infinite loops • Counters and accumulators • For…Next statement 2

Repetition Structures (1 of 2) • • • Repetition structure, referred to more simply as a loop, need the computer to repeatedly process one or more program instructions. The condition for repeating the instructions is referred to as the looping condition. The condition for not repeating the instructions is referred to as the loop exit condition. – Condition evaluated before the instructions is referred as pretest loop. – Condition evaluated after the instructions is referred a posttest loop. 3

Repetition Structures (2 of 2) 4

Do…Loop Statement (Pretest Loop) 5

String Concatenation • Concatenation operator, the ampersand (&), is used to concatenate (connect or link together) strings. • The Control. Chars. New. Line constant advances the insertion point to the next line. 6

Do…Loop Statement (Posttest Loop) 7

Counters and Accumulators (1 of 2) • A counter is a numeric variable used for counting something. • An accumulator is a numeric variable used for accumulating. 8

Counters and Accumulators (2 of 2) • Incrementing - adding 1 to a number • Decrementing - subtracting 1 from a number 9

For…Next Statement (1 of 4) • For…Next statement can be used to code only a specific type of pretest loop. • A counter-controlled loop is a loop whose processing is controlled by a counter. – Counter variable has block scope and can be used only within the For…Next loop. – As data. Type portion of the For clause is used to declare the counter variable. 10

For…Next Statement (2 of 4) 11

For…Next Statement (3 of 4) Comparing the For…Next and Do…Loop Statements 12

For…Next Statement (4 of 4) Flowcharts comparing the Do…Loop and For…Next Statements 13

APPLY THE CONCEPTS LESSON After studying this lesson, you should be able to: • Add a list box to a form • Use the methods and a property of the Items collection • Calculate a periodic payment • Nest repetition structures • Professionalize your application’s interface 14

Add a List Box to a Form (1 of 14) • A list box displays a list of items. • The number of items to be selected at any one time is determined by the list box’s Selection. Mode property 15

Add a List Box to a Form (2 of 14) Using the String Collection Editor to Add Items to a List Box: • The items in a list box belong to a collection called the Items collection. – A collection is a group of individual objects treated as one unit. • The String Collection Editor provides an easy way to add items to the Items collection. 16

Add a List Box to a Form (3 of 14) To use the String Collection Editor: • Open the List. Box Solution. sln file contained in the List. Box Solution folder. • Click the lst. States list box and then click Items in the Properties window. • Click the. . . (ellipsis) button and then enter the four state IDs : TN, KY, SD, and SC. • Click the OK button. • Save the solution and then start the application. • The four state IDs appear in the same order as they do in the String Collection Editor: TN, KY, SD, and SC. • Click the Exit button. 17

Add a List Box to a Form (4 of 14) 18

Add a List Box to a Form (5 of 14) • The sorted property : – to sort the items in a list box – Dictionary order – numbers are sorted before letters, and – a lower case letter is sorted before uppercase • To sort the items in the Ist. States control: – Set the Ist. States control’s sorted property to True. – Save the solution and then start the application. § The state IDs are now sorted in ascending order. – Click the Exit button. 19

Add a List Box to a Form (6 of 14) The Selected. Item and Selected. Index Properties • The selected item in a list box is called the default list box item. – Use either the Selected. Item property or the Selected. Index property to select the default list box item from code. • Load event occurs when the application is started and the form is displayed the first time. 20

Add a List Box to a Form (7 of 14) 21

Add a List Box to a Form (8 of 14) To select the first item in the list box: • Open the Code Editor window. • Click (frm. Main Events) in the Object list box and then click Load in the Event list box. • Enter the comment and assignment statement. lst. States. Selected. Index = 0 • Save the solution and then start the application. – Notice that the first item in the list is selected (highlighted). • Click the Exit button. 22

Add a List Box to a Form (9 of 14) To display the selected item and its index: • Locate the btn. Selected_Click procedure. • Click the blank line above the End Sub clause and then enter the assignment statements. • Save the solution and then start the application. • Click the Selected button. – KY and 0 appear in the Item and Index boxes. • Click SD in the list box. Click the Selected button. – SD and 2 appear in the Item and Index boxes, respectively. • Click the Exit button. 23

Add a List Box to a Form (10 of 14) 24

Add a List Box to a Form (11 of 14) The Selected. Value. Changed and Selected. Index. Changed Events: • Selected. Value. Changed event and Selected. Index. Changed event occur when either the user or a statement selects an item in a list box • Code lst. States_Selected. Index. Changed procedure to clear the contents of the Item and Index boxes 25

Add a List Box to a Form (12 of 14) To code the Selected_Index. Changed procedure: • Open the code template for the lst. States_Selected. Index. Changed procedure and then enter the comment and two assignment statements. • Save the solution and then start the application. • Click the Selected button. – KY and 0 appear in the Item and Index boxes, respectively. 26

Add a List Box to a Form (13 of 14) • Click SD in the list box. – The lst. States_Selected. Index. Changed procedure clears the contents of the Item and Index boxes. • Click the Selected button. – SD and 2 appear in the Item and Index boxes, respectively. • Click the Exit button. • Close the Code Editor window and then close the solution. 27

Add a List Box to a Form (14 of 14) 28

Use the Methods and a Property of the Items Collection (1 of 7) • Add method – to add items to a list box 29

Use the Methods and a Property of the Items Collection (2 of 7) To use the Add method: • Open the List. Box Items Solution. sln file contained in the List. Box Items Solution folder. • Open the Code Editor window and locate the frm. Main_Load procedure. – Click the blank line above the End Sub clause and then enter the For…Next loop and assignment statement. – The frm. Main_Load procedure adds the numbers from 1 through 25 to the list box and then selects the first number (1). • Save the solution and then start the application. 30

Use the Methods and a Property of the Items Collection (3 of 7) 31

Use the Methods and a Property of the Items Collection (4 of 7) 32

Use the Methods and a Property of the Items Collection (5 of 7) Count Property: • The Items collection’s Count property stores an integer that represents the number of list box items. To use the Count property: • Locate the btn. Count_Click procedure. • Click the blank line above the End Sub clause and then enter following assignment statement: lbl. Items. Text = lst. Nums. Items. Count. To. String • Save the solution and then start the application. • Click the Count button. The number 25 appears in the Items box. Click the Exit button. 33

Use the Methods and a Property of the Items Collection (6 of 7) Clearing the Items from a List Box: • The Items collection provides a Clear method for clearing (removing) the items from a list box. – The method’s syntax is object. Items. Clear() To use the Clear method: • Locate the btn. Clear_Click procedure. • Click the blank line above the End Sub clause and then enter the following two statements: lst. Nums. Items. Clear() lbl. Items. Text = String. Empty 34

Use the Methods and a Property of the Items Collection (7 of 7) • Save the solution and then start the application. • Click the Count button, which displays the number 25 in the Items box. • Click the Clear button to clear the items from the list box, and then click the Count button. – The number 0 appears in the Items box. • Click the Exit button. • Close the Code Editor window and then close the solution. 35

Calculate a Periodic Payment (1 of 6) • The Monthly Payment application uses the Financial. Pmt method to calculate a monthly mortgage payment. 36

Calculate a Periodic Payment (2 of 6) To code and then test the Monthly Payment application: • Open the Payment Solution. sln file contained in the Payment Solution folder. • Open the Code Editor window, which already contains the code for many of the application’s procedures. • Locate the frm. Main_Load procedure. • Click the blank line above the End Sub clause and then enter the For…Next loop and assignment statement. (For dbl. Rates As Double = 2 To 7 Step 0. 5) – Be sure to change the Next clause to Next dbl. Rates. 成品 37

Calculate a Periodic Payment (3 of 6) To code and then test the Monthly Payment application: • Save the solution and then start the application. • Verify that the list box contains the appropriate rates and that the 3. 0 rate is selected. • Click the Exit button. • Locate the btn. Calc_Click procedure. • Click the blank line above the End Sub clause. • Enter a Try. Parse method that assigns the rate selected in the list box to the dbl. Rate variable. (Double. Try. Parse(lst. Rates. Selected. Item. To. String, dbl. Rate) ) 38

Calculate a Periodic Payment (4 of 6) • • • Next, you will convert the rate to its decimal equivalent by dividing it by 100. Type dbl. Rate = dbl. Rate / 100 and press Enter twice. Before calculating and displaying the monthly payments, you will clear any previous payments from the lbl. Pay control. – Type lbl. Pay. Text = String. Empty and press Enter. • Finally, enter a For…Next loop that calculates and displays the monthly payments for terms of 15, 20, 25, and 30 years. (For int. Term As Integer = 15 To 30 Step 5) – Be sure to change the Next clause to Next int. Term. 成品 39

Calculate a Periodic Payment (5 of 6) • Open the code template for the lst. Rates_Selected. Index. Changed procedure. – Have this procedure clear the contents of the lbl. Pay control when a change is made to the rate selected in the lst. Rates control. – Type lbl. Pay. Text = String. Empty and press Enter. • Save the solution and then start the application. • Type 125000 in the Principal box and then click the Calculate button. – The monthly mortgage payments appear in the interface. 結果 40

Calculate a Periodic Payment (6 of 6) • Test the application using different principals and rates. – Verify that the Monthly payment box is cleared when a change is made to either the principal or the rate. • When you are finished testing, click the Exit button. • Close the Code Editor window and then close the solution. Agrees with Example 2 of slide 36 41

Nest Repetition Structures (1 of 7) • Like selection structures, repetition structures can be nested (place one loop within another loop) (called the outer loop). • Both loops can be either pretest loops or posttest loops. Or, one can be a pretest loop and the other a posttest loop. 42

Nest Repetition Structures (2 of 7) Nested Repetition Structure Example: Savings Account Application • A text box’s Multiline property is set to True, when the text box can accept and display multiple lines of text. • Changing a text box’s Read. Only property from its default value (False) to True prevents the user from changing the contents of the text box during run time. • A text box’s Scroll. Bars property specifies whether the text box has no scroll bars (the default), a horizontal scroll bar, a vertical scroll bar, or both horizontal and vertical scroll bars. 43

Nest Repetition Structures (3 of 7) 成品 44

Nest Repetition Structures (4 of 7) • Control. Chars. Tab constant represents the Tab key to align the information. To code and then test the btn. Calc_Click procedure: • Open the Savings Solution. sln file contained in the Savings Solution folder. • Open the Code Editor window and locate the btn. Calc_Click procedure. – The first three steps in the pseudocode have already been coded for you. • Click the blank line above the End Sub clause and then enter the outer and nested Loops. 45

Nest Repetition Structures (5 of 7) 46

Nest Repetition Structures (6 of 7) • Save the solution and then start the application. • Type 2500 in the Deposit text box and then click the Calculate button. • Scroll the text box to verify that it contains the account balances for each of the five rates. • Click the Exit button. • Close the Code Editor window and then close the solution. 47

Nest Repetition Structures (7 of 7) 48

Professionalize Your Application’s Interface (1 of 2) • When the default button is selected, the computer processes the code contained in the button’s Click event procedure. • Specify the default button by setting the form’s Accept. Button property to the name of the button. • Cancel. Button property allows the user to select a button by pressing the Esc key. • A default button should be the button that is most often selected by the user. 49

Professionalize Your Application’s Interface (2 of 2) To designate a default button in the Savings Account application from the previous section: • Display the form’s properties in the Properties window. Set the Accept. Button property to btn. Calc. A darkened border now appears around the Calculate button. • Save the solution and then start the application. – Type 5000 in the Principal box and then press Enter. – The computer processes the code contained in the btn. Calc_Click procedure, and the savings account balances appear in the txt. Balance control. • Click the Exit button and then close the solution. 50

Summary (1 of 6) • You use a repetition structure (loop) when you need the computer to repeatedly process one or more program instructions. • The loop’s condition can be phrased as either a looping condition or a loop exit condition. • • • The condition must evaluate to either True or False. A looping condition indicates when the computer should continue processing the loop body. A loop exit condition indicates when the computer should stop processing the loop body. In a pretest loop, the condition is evaluated before the loop body is processed. In a posttest loop, the condition is evaluated after the loop body is processed. 51

Summary (2 of 6) • • • The loop body in a posttest loop will always be processed at least once. Depending on the result of the condition, the loop body in a pretest loop may never be processed. Use the Do…Loop statement to code a pretest loop. Use the Do…Loop statement to code a posttest loop. In a flowchart, you use the decision symbol (a diamond) to represent a loop’s condition. To concatenate strings: Use the concatenation operator (&). 52

Summary (3 of 6) • • • You can use the Control. Chars. New. Line constant to advance the insertion point to the next line. You can stop an endless (infinite) loop by clicking Debug and then clicking Stop Debugging. – Or, you click the Stop Debugging button (the red square) on the Standard toolbar. Counters and accumulators need to be initialized and updated. – A counter is usually initialized to either 0 or 1; – an accumulator is usually initialized to 0. – A counter is updated by either incrementing or decrementing its value by a constant amount, which can be either positive or negative, integer or noninteger. – An accumulator is typically updated by incrementing its value by an amount that varies. 53

Summary (4 of 6) • • • To use the For…Next statement to code a countercontrolled loop: If the counter variable is declared in the For clause, it has block scope and can be used only within the For…Next loop. When using the For…Next statement, the number of iterations the loop will perform is controlled by the For clause’s start. Value, end. Value, and step. Value. – The start. Value, end. Value, and step. Value must be numeric and can be positive or negative, integer or noninteger. – If you omit the step. Value, a step. Value of positive 1 is used. 54

Summary (5 of 6) • An overflow error occurs when the value assigned to a memory location is too large for the location’s data type. • A Do…Loop’s body must contain an instruction that will stop the loop. • You can use the List. Box tool in the toolbox to add a list box to a form. • A list box’s Selection. Mode property determines whether the user can select zero items, one item, or multiple items. 55

Summary (6 of 6) • • You can use either the String Collection Editor or the Items collection’s Add method to add items to a list box. When a list box’s Sorted property is set to True, the list box items appear in ascending order; otherwise, they appear in the order they are added to the list box. To determine the item selected in a list box or to select a list box item from code, use either the list box’s Selected. Item property or its Selected. Index property. When no item is selected in a list box, the Selected. Item property contains the keyword Nothing (which means it does not contain any data) and the Selected. Index property contains – 1 (negative one). 56
- Slides: 56