Upload
rhoda-hines
View
228
Download
3
Tags:
Embed Size (px)
Citation preview
Lecture Set 5
Control StructuresPart 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 …
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
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
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
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
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
Slide 8
Execution Flow of a Do Until Loop
Slide 9
Execution Flow of a Do While Loop
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
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
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
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
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
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
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.
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
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
Slide 19
For Loops (Syntax)
For counter = start To end [Step increment]
[statements] [Exit For] [statements]Next [counter]statements
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
Slide 21
For Loops (Example)
Print the counting numbers 1 to 10Dim Counter As IntegerFor Counter = 1 To 10 Debug.WriteLine(Counter)Next Counter
Slide 22
Execution of a For Loop
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
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
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)
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
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
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
Slide 29
Setting Breakpoints (A For loop with a breakpoint and an Execution Point)
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.