Top Banner
Chapter 6: The Repetition Structure Programming with Microsoft Visual Basic .NET, Second Edition
68
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 6

Chapter 6: The Repetition Structure

Programming with Microsoft Visual Basic .NET, Second Edition

Page 2: Chapter 6

2

Homework/Project #1 : Calculator

Due: 03/02

Page 3: Chapter 6

3

Homework #1 Calculator

• Use Message boxes to inform user of eventual problems. For example:– Division by 0 forbidden!

Page 4: Chapter 6

4

The Basic FOR LoopThe Basic FOR Loop

• A counter loop is also known as a For loop, or a For/Next loop.

• You use a counter loop when you want the computer to perform a task a specific number of times.

Page 5: Chapter 6

5

FOR LoopFOR Loop Flowchart Flowchart

Set control variable to initial value

Iscontrol variable >

terminating value?

Execute statements within loop

Increment control variable (automatic)

Execute statements following the loop

Yes

No

Page 6: Chapter 6

6

The For…Next Loop (continued)The For…Next Loop (continued)

Figure 6-4: Pseudocode and flowchart for the first example shown in Figure 6-2

Page 7: Chapter 6

7

FOR Loop useFOR Loop use

For ControlVariable= InitVal To TerminatingVal [Step StepSize]

Statement(s) to be Repeated

Next ControlVariable

Dim intCounter as integer

For intCounter =1 To 10

txtDisplay.Text = txtDisplay.Text & convert.toString(IntCounter)

Next intCounter

1 2 3 4 5 6 7 8 9 10Screen Output

Page 8: Chapter 6

8

FOR Loop useFOR Loop use

Dim intStar as integer

For intStar =1 To 15

lblDisplay.Text = lblDisplay.Text & " * "

Next intStar

* * * * * * * * * * * * * * *Screen Output

Page 9: Chapter 6

9

Exiting from a loop before it Exiting from a loop before it endsends

2 ways:

#1 Assign a value to the control variable that will make the loop condition false (> terminating value)

For intLoop = 1 to 1000…if intTime > 100 then

intLoop=9999end if…

Next

Page 10: Chapter 6

10

Exiting from a loop before it Exiting from a loop before it endsends

2 ways:

#2 Use Exit for statement (recommended)

For intLoop = 1 to 1000…if intTime > 100 then

Exit forend if…

Next

Page 11: Chapter 6

11

FOR Loop ExerciseFOR Loop Exercise

• Write the code to display the first 10 odd numbers.

1 – 3 – 5 – 7 – 9 – 11 – 13 – 15 - 17 - 19

Page 12: Chapter 6

12

FOR Loop ExerciseFOR Loop Exercise

Dim intCounter as Integer

For IntCounter = 1 to 19 step 2

lblDisplay.text = lblDisplay.Text & convert.toString(IntCounter) & “ - “

Next IntCounterOR

For IntCounter = 1 to 10

lblDisplay.Text = lblDisplay.Text & convert.toString (IntCounter*2) & “ - “

Next IntCounter

Page 13: Chapter 6

13

Structured program designStructured program design

• Control structures:

– Sequence control structure (one program statement follows another in logical order).

– Selection control structure (represents choices)

– Iteration, loop structure (when a process may be repeated as long as a certain condition remains true.)

Page 14: Chapter 6

14

• There are 3 types of iteration structures:

• For (condition) Loop

• Do While (condition)

• Do Until (condition)

Iteration Control StructureIteration Control Structure

Page 15: Chapter 6

15

Do While Control StructureDo While Control Structure

strPassword=InputBox(“Password?”)

Do While strPassword <> “007”

strPassword=InputBox(“Password?”)

Loop

Loopstatements

Yes

No

Do While Condition Statement(s)Loop

Do While(Test condition)

Page 16: Chapter 6

16

Do Until Control StructureDo Until Control Structure

Loopstatement(s)

Do Until(test condition)

Yes

No

Do Statement(s)Loop Until Condition

Do

strPassword = InputBox(“Password?”)

Loop Until strPassword = “007”

Page 17: Chapter 6

17

Difference between Do While / Do UntilDifference between Do While / Do Until

• If there are several statements that need to be repeated, you need to decide when to stop repeating them.

• You can decide to stop them:

– at the beginning of the loop, using Do While

– or at the end of the loop using Do Until

Page 18: Chapter 6

18

Difference between Do While / Do UntilDifference between Do While / Do Until

• The Do Until iterations means that the loop

statement will be executed at least once.

This is because the iteration statements are

executed before you asked whether to stop.

Page 19: Chapter 6

19

The Do…Loop Statement The Do…Loop Statement (continued)(continued)

Figure 6-7: Syntax and examples of the Do...Loop statement

Page 20: Chapter 6

20

Exit to a Loop statementExit to a Loop statementDo

StatementsIf condition then Exit Do Provide an alternate way to exit a loop

End If StatementsLoop Until condition

Do While conditionStatementsExit DoStatements

Loop

Page 21: Chapter 6

21

ExerciseExercise

• Write a program to display all the numbers between 1 and 1000 that are perfect squares. (A perfect square is an integer that is the square of another integer; 1,4,9,16, …)

• Use: #1 Do While

#2 Do Until

#3 For Next

Page 22: Chapter 6

22

Exercise SolutionExercise Solution

Dim intX, intY as integer

intX=1

IntY = IntX * IntX

lblDisp.text= "The perfect squares between 1 and 1000 are"

Do While IntY <= 1000 Do

lblDisp.text= lblDisp.text & lblDisp.text =lblDisp.text &

conver.toString(IntY) & “,” conver.toString(IntY) & “,”

IntX = IntX + 1 IntX = IntX + 1

IntY = IntX * IntX IntY = IntX * IntX

Loop Loop Until IntY >= 1000

1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289,

324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961

Page 23: Chapter 6

23

Exercise SolutionExercise Solution

lblDisp.text= "The perfect squares between 1 and 1000 are"

For intX=1 to 100 (Could have used another end value)

intY = intX * intX

If intY > 1000 Then

Exit For

Else

lblDisp.text=convert.toString(IntY)

End If

Next IntX

Page 24: Chapter 6

24

Exercise #7Exercise #7Exercise #7

By default hidden – visible after number have been displayed

Page 25: Chapter 6

25

Lab ExercisesLab Exercises

• #8 Display a row of 50 stars (asterisks).

• #9 Request a number from 1 to 20 (using an input box) and display a row of that many stars. If number >20 or <1 display a warning message (message box) and request the number again.

Page 26: Chapter 6

26

Lab ExerciseLab Exercise

• #10 Find the sum 1 + ½ + 1/3 + ¼ + … + 1/100 Solution: 5.187378

• #11 You are offered two salary options for ten days of work.

Option 1: $100 per day

Page 27: Chapter 6

27

Lab ExerciseLab Exercise

Option2: $1 the first day, $2 the second day, $4 the third day, and so on, with the amount of doubling each day.

Write a program to determine which option pays better.

Solution: Option1: $1000 Option 2: $1023

Page 28: Chapter 6

That’s all Folks!That’s all Folks!

Page 29: Chapter 6

Chapter 6: The Repetition Structure

Programming with Microsoft Visual Basic .NET, Second Edition

Page 30: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 30

The Repetition Structure (Looping)Lesson A Objectives

• Code the repetition structure using the For...Next and Do...Loop statements

• Write pseudocode for the repetition structure

• Create a flowchart for the repetition structure

• Initialize and update counters and accumulators

Page 31: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 31

The Repetition Structure

• Use the repetition structure to repeatedly process one or more program instructions until some condition is met, at which time the repetition ends

• The repetition structure is referred to as a loop

Page 32: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 32

The Repetition Structure (continued)

• Pretest loop: evaluation occurs before the instructions within the loop are processed

• Posttest loop: evaluation occurs after the instructions within the loop are processed

Page 33: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 33

The For…Next Loop

• Use the For…Next statement to code a loop that repeats for a specific number of times

Figure 6-2: Syntax and examples of the For...Next statement

Page 34: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 34

The For…Next Loop (continued)

Figure 6-2: Syntax and examples of the For...Next statement (continued)

Page 35: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 35

The For…Next Loop (continued)

• counter is a numeric variable that keeps track of how many times the loop instructions are repeated

• startvalue, endvalue, and stepvalue

– Must be numeric

– Can be positive or negative, integer or non-integer

– Default stepvalue is 1

Page 36: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 36

The For…Next Loop (continued)

Figure 6-4: Pseudocode and flowchart for the first example shown in Figure 6-2

Page 37: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 37

The For…Next Loop (continued)

Dim count As Integer

For count = 0 to 3 Step 1

Debug.WriteLine(count)

Next count

Dim count As Integer

For count = 3 to 0 Step -1

Debug.WriteLine(count)

Next count

Dim count As Integer

For count = 0 to 10 Step 2

Debug.WriteLine(count)

Next count

Dim loc As Single

For loc = 0.5 To 15 Step 0.5

Debug.WriteLine(loc)

Next loc

For…Next loop examples:

Page 38: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 38

The Do…Loop Statement

• Unlike the For…Next statement, the Do…Loop statement can be used to code both a pretest loop and a posttest loop

• The Do…Loop statement begins with the Do clause and ends with the Loop clause

Page 39: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 39

The Do…Loop Statement (continued)

Figure 6-7: Syntax and examples of the Do...Loop statement

Page 40: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 40

The Do…Loop Statement (continued)

Figure 6-7: Syntax and examples of the Do...Loop statement (continued)

Page 41: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 41

The Do…Loop Statement (continued)

Figure 6-9: Flowcharts for the examples shown in Figure 6-7

Page 42: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 42

The Do…Loop Statement (continued)

Figure 6-9: Flowcharts for the examples shown in Figure 6-7 (continued)

Page 43: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 43

Using Counters and Accumulators

• Counters and accumulators are used within a repetition structure to calculate subtotals, totals, and averages

• A counter is a numeric variable used for counting something and is typically updated by 1

• An accumulator is a numeric variable used for accumulating and is updated by an amount that varies

Page 44: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 44

Using Counters and Accumulators (continued)

• Initializing: assigning a beginning value to the counter or accumulator

• Updating (incrementing): adding a number to the value stored in the counter or accumulator

Page 45: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 45

Nested Repetition StructuresLesson B Objectives

• Nest repetition structures

Page 46: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 46

Nesting Repetition Structures

• In a nested repetition structure, one loop, referred to as the inner loop, is placed entirely within another loop, called the outer loop

• A clock uses nested loops to keep track of the time

Page 47: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 47

Nesting Repetition Structures (continued)

Figure 6-16: Nested loops used by a clock

Page 48: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 48

The Grade Calculator Application

• Professor Arkins needs an application that allows him to assign a grade to any number of students

• Each student’s grade is based on three test scores, with each test worth 100 points

• The application should total the test scores and then assign the appropriate grade, using the table shown on the next slide

Page 49: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 49

The Grade Calculator Application (continued)

Total points earned Grade

270–300 A

240–269 B

210–239 C

180–209 D

below 180 F

Page 50: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 50

The Grade Calculator Application (continued)

• uiAssignGradeButton’s Click event procedure

– Allows Professor Arkins to enter each student’s test scores, and then assign the appropriate grade

– Contains two loops, one nested within the other

– A For...Next statement controls the inner loop

Page 51: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 51

The Grade Calculator Application (continued)

• uiAssignGradeButton’s Click event procedure (continued)

– A Do...Loop statement controls the outer loop

– The inner loop is a pretest loop

– The outer loop is a posttest loop

Page 52: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 52

The Grade Calculator Application (continued)

Figure 6-20: Sample run of the application that contains the procedure

Page 53: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 53

Coding the Shoppers Haven Application

Lesson C Objectives• Select the existing text in a text box

• Prevent a form from closing

Page 54: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 54

Shoppers Haven

• The manager of Shoppers Haven wants an application that the store clerks can use to calculate the discounted price of an item, using discount rates from 10% through 30% in increments of 5%

• The clerks will enter the item’s original price

• The application should display the discount rates and the discounted prices in the interface

Page 55: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 55

Shoppers Haven (continued)

Figure 6-21: User interface for the Shoppers Haven application

Page 56: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 56

Shoppers Haven (continued)

Figure 6-22: TOE chart for the Shoppers Haven application

Page 57: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 57

Shoppers Haven (continued)

Figure 6-23: Pseudocode for the Calculate button’s Click event procedure

Page 58: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 58

Shoppers Haven (continued)

Figure 6-27: Discounted prices shown in the Shoppers Haven application

Page 59: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 59

Selecting the Existing Text in a Text Box

• Use the SelectAll method to select all of the text contained in a text box

• Syntax: textbox.SelectAll()

• textbox is the name of the text box whose text you want to select

Page 60: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 60

Selecting the Existing Text in a Text Box (continued)

• Enter the SelectAll method in a text box control’s Enter event

• A text box control’s Enter event occurs when the user tabs to the control, and when the Focus method is used in code to send the focus to the control

• The uiOriginalTextBox control’s Enter event is responsible for highlighting the existing text in the control

Page 61: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 61

Selecting the Existing Text in a Text Box (continued)

Figure 6-29: Text selected in the Shoppers Haven application

Page 62: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 62

Coding the TextChanged Event Procedure

• A control’s TextChanged event occurs when the contents of a control’s Text property change

• Use the uiOriginalTextBox’s TextChanged event to clear the contents of the uiDiscPricesLabel when the user changes the original price

Page 63: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 63

Coding the ShoppersForm’s Closing Event Procedure

• A form’s Closing event occurs when a form is about to be closed

• In the Shoppers Haven application, the Closing event procedure is responsible for:

– Verifying that the user wants to exit the application

– Taking an action based on the user’s response

Page 64: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 64

Coding the ShoppersForm’s Closing Event Procedure (continued)

Figure 6-31: Pseudocode for the ShoppersForm’s Closing event procedure

Page 65: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 65

Coding the ShoppersForm’s Closing Event Procedure (continued)

Figure 6-33: Message box displayed by the form’s Closing event

Page 66: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 66

Summary

• Repetition structure (loop): the computer repeats a set of instructions until some condition is met

• Code a repetition structure in Visual Basic .NET using one of the following statements: For...Next, Do...Loop, and For Each…Next

• The For...Next statement is pretest loops only

• The Do...Loop statement can code pretest and posttest loops

Page 67: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 67

Summary (continued)

• To use a counter or accumulator:

– Initialize, if necessary

– Update using an assignment statement in a repetition structure

• To nest a repetition structure, place the entire inner loop within the outer loop

Page 68: Chapter 6

Programming with Microsoft Visual Basic .NET, Second Edition 68

Summary (continued)

• To process code when the user tabs to a control, or when the Focus method is used in code to send the focus to the control, enter the code in the control’s Enter event procedure

• To process code when a form is about to be closed, enter the code in the form’s Closing event procedure