lecture set 5 control structures part d - repetition with loops

30
Lecture Set 5 Control Structures Part D - Repetition with Loops

Upload: rhoda-hines

Post on 30-Dec-2015

219 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Lecture Set 5 Control Structures Part D - Repetition with Loops

Lecture Set 5

Control StructuresPart D - Repetition with Loops

Page 2: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 2

Objectives

Write Do loops to execute statements repeatedly

Write For loops to execute statements repeatedly

Learn the differences between For and Do loops (and Do While and Do Until)

Lear how to use loop Exit and Continue

This material should mostly review so it should go quickly – you have seen most of it already …

Page 3: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 3

Introduction to Loops

These structures are part of nearly every program written

Repetition is the most powerful feature of any language – it is what computers do best (and FAST!)

Learning how to construct loops with appropriate loop parameters can make difficult tasks seem easy (and coded with a short instruction sequence

Page 4: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 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

Page 5: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 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

Page 6: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 6

Do While and Do Until Loops (Syntax)

Do While and Do Until loops execute statements repeatedlyDo [While | Until] condition [statements] [Exit Do] [statements]Loopstatements

Page 7: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 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 Exit Do statement causes the Do loop to

exit immediately statements following the loop execute

Page 8: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 8

Execution Flow of a Do Until Loop

Page 9: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 9

Execution Flow of a Do While Loop

Page 10: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 10

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

Page 11: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 11

Loops and Counters (Example)

Print the counting numbers 1 through 10 using a Do Until loop

Dim Counter As Integer = 1Do Until Counter > 10 Debug.WriteLine(Counter) Counter += 1Loop

Page 12: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 12

Loops and Counters (Example, continued)

Print the counting numbers 1 through 10 using a Do While loop

Dim Counter As Integer = 1Do While Counter <= 10 Debug.WriteLine(Counter) Counter += 1Loop

Page 13: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 13

The Role of an Accumulator

An accumulator is similar to a counter An accumulator is updated each time the

statements in a loop execute It can be used to calculate (accumulate) a

total An accumulator usually takes the

following general form: Accumulator = Accumulator + value Accumulator += value

But we will see other forms of “accumulators” as well – they are a powerful programming tool

Page 14: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 14

Accumulator (Example)

Store the sum of the counting numbers 1 through 10

Dim Counter As Integer = 1Dim Accumulator As Integer = 0Do While Counter <= 10 Debug.WriteLine(Counter) Accumulator += Counter Counter += 1Loop

Page 15: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 15

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 = 1Do While Counter < 10 Debug.WriteLine(Counter)Loop

Page 16: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 16

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

HOWEVER – it is generally a good idea NOT to nest loops inside loops or decisions. Put them in a separate procedure instead.

Page 17: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 17

Combining Looping and Decision-making Statements (Example)

Determine whether a number is primePrivate 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

Page 18: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 18

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

Page 19: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 19

For Loops (Syntax)

For counter = start To end [Step increment]

[statements] [Exit For] [statements]Next [counter]statements

Page 20: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 20

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

Page 21: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 21

For Loops (Example)

Print the counting numbers 1 to 10Dim Counter As IntegerFor Counter = 1 To 10 Debug.WriteLine(Counter)Next Counter

Page 22: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 22

Execution of a For Loop

Page 23: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 23

Nested For Loop (Example (to be avoided) )

Print a multiplication tableDim Factor1, Factor2, Result As IntegerFor Factor1 = 1 To 10 For Factor2 = 1 To 10 Result = Factor1 * Factor2 Debug.Write(Result.ToString() & " ") Next Debug.WriteLine("")Next

Page 24: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 24

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

Page 25: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 25

Exit and Continue Statements

Can be used with any loop form Exit causes the innermost loop that

contains it to exit immediately, sending control to the first instruction that follows the loop

Continue causes the innermost loop that contains it to repeat immediately (effectively sending control to the bottom of the loop so that loop repetition can take place)

The keywords Exit and Continue must be followed by keywords indicating the type of loop they are used in (Exit For or Exit Do)

Page 26: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 26

The Exit Statement

A loop with an Exit statement Dim message as String = Nothing Dim monthlyInvestment As Decimal Dim monthlyInterestRate As Decimal Dim months As Integer Dim futureValue As Decimal For i As Integer = 1 To months futureValue = (futureValue + monthlyInvestment) _ * (1 + monthlyInterestRate) If futureValue > 1000000 Then message = "Future value is too large." Exit For ' the For loop ends End If Next i

Page 27: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 27

The Continue Statement

A loop with a Continue statement Dim sumNumbers as Integer Dim sumBigNumbers As Integer For i as Integer = 1 To 6 sumNumbers += i If i < 4 Then Continue For End If sumBigNumbers += i Next i

Page 28: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 28

The Implications of Long-running Loops

Some loops can run for hours Display messages periodically in long-

running loops, or Show a progress bar as the loop is running

so the user knows that progress is being made

Improve the performance of long-running loops where possible Move unnecessary statements outside of a

loop

Page 29: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 29

Setting Breakpoints (A For loop with a breakpoint and an Execution Point)

Page 30: Lecture Set 5 Control Structures Part D - Repetition with Loops

Slide 30

Setting and Clearing Breakpoints

How to set and clear breakpoints To set a breakpoint, click in the margin indicator bar to the left of

a statement. Or, press the F9 key to set a breakpoint at the cursor insertion point. Then, a red dot will mark the breakpoint.

To remove a breakpoint, use either technique for setting a breakpoint. To remove all breakpoints at once, use the Clear All Breakpoints command in the Debug menu.

How to work in break mode In break mode, a yellow arrowhead marks the current execution

point, which points to the next statement that will be executed.

To step through your code one statement at a time, press the F11 key or click the Step Into button on the Debug toolbar.

To continue normal processing until the next breakpoint is reached, press the F5 key.