25
1 CS 106 Computing Fundamentals II Chapter 61 “Loops” Herbert G. Mayer, PSU CS Herbert G. Mayer, PSU CS Status 7/29/2013 Status 7/29/2013 Initial content copied verbatim from Initial content copied verbatim from CS 106 material developed by CS 106 material developed by CS professors: Cynthia Brown & Robert Martin CS professors: Cynthia Brown & Robert Martin

1 CS 106 Computing Fundamentals II Chapter 61 “Loops” Herbert G. Mayer, PSU CS Status 7/29/2013 Initial content copied verbatim from CS 106 material developed

Embed Size (px)

Citation preview

1

CS 106Computing Fundamentals II

Chapter 61“Loops”

Herbert G. Mayer, PSU CSHerbert G. Mayer, PSU CSStatus 7/29/2013Status 7/29/2013

Initial content copied verbatim fromInitial content copied verbatim fromCS 106 material developed byCS 106 material developed by

CS professors: Cynthia Brown & Robert MartinCS professors: Cynthia Brown & Robert Martin

2

Syllabus RepetitionRepetition

Real-Life ExamplesReal-Life Examples

Multiplication Table ExampleMultiplication Table Example

For Next LoopFor Next Loop

Do WhileDo While

Do UntilDo Until

Nested LoopsNested Loops

3

Repetition

• Repetition of the same or similar actions is often Repetition of the same or similar actions is often needed in process designneeded in process design

• Three styles of repetition:Three styles of repetition: Repeat for a fixed number of times Repeat as long as or while a certain condition is true Repeat until a condition becomes true Repeat for every element of a group or set

• We’ll look at the first two types in this sessionWe’ll look at the first two types in this session

3

4

Real-Life Examples

• Keep ringing up items while the customer has moreKeep ringing up items while the customer has more

• Keep adding numbers until you get to the known end Keep adding numbers until you get to the known end of the listof the list

• Cut a paycheck for each employee in the rosterCut a paycheck for each employee in the roster

4

5

Multiplication Table Example

5

6

Printing a Multiplication Table

• Our job: input a number between 1 and 12 in a text Our job: input a number between 1 and 12 in a text box (txtM)box (txtM)

• Print a multiplication table for this number in a list Print a multiplication table for this number in a list box (lstAnswer)box (lstAnswer)

• This is possible but painful with our current set of This is possible but painful with our current set of toolstools

6

7

Possible code…

strM = txtM.Text strM = txtM.Text 'text form of M'text form of M

numM = numM = CIntCInt(strM) (strM) 'numeric form of M'numeric form of M

lstAnswer.ClearlstAnswer.Clear ‘nothing in the list box‘nothing in the list box

lstAnswer.AddItem( strM & " X 1 = " & lstAnswer.AddItem( strM & " X 1 = " & CStrCStr(numM * 1 ) )(numM * 1 ) )

lstAnswer.AddItem( strM & " X 2 = " & lstAnswer.AddItem( strM & " X 2 = " & CStrCStr(numM * 2 ) )(numM * 2 ) )

lstAnswer.AddItem( strM & " X 3 = " & lstAnswer.AddItem( strM & " X 3 = " & CStrCStr(numM * 3 ) )…(numM * 3 ) )…

lstAnswer.AddItem( strM & " x 12 = " & lstAnswer.AddItem( strM & " x 12 = " & CStrCStr(numM * 12 ) )(numM * 12 ) )

7

8

Ugh!

• This is clumsy and unbearably repetitiveThis is clumsy and unbearably repetitive

• If we wanted to change the upper limit in some way If we wanted to change the upper limit in some way (say do up to 8 * 8, or 10 * 10, instead of going to 12 (say do up to 8 * 8, or 10 * 10, instead of going to 12 each time), we would need even uglier codeeach time), we would need even uglier code

• Doing a large number of these would be awfulDoing a large number of these would be awful

• Luckily, VBA has some nice repetition constructsLuckily, VBA has some nice repetition constructs

• Now for some samples with upper bounds, 4 or 10 . . .Now for some samples with upper bounds, 4 or 10 . . .

8

9

For Next loop

• Repetitions are called loops in VBARepetitions are called loops in VBA

• Loops go through, what we call, Loops go through, what we call, iterationsiterations; or we say: ; or we say: loops iterateloops iterate

• A A For Next For Next loop is used when we can determine the loop is used when we can determine the number of repetitions before starting the loopnumber of repetitions before starting the loop

• Such determinations can be computable trivially, if Such determinations can be computable trivially, if the so called the so called upper bound upper bound is a constantis a constant

• Or else, if the bound is computable at the latest by Or else, if the bound is computable at the latest by the start of the first loop iterationthe start of the first loop iteration

9

10

Simple For Next LoopstrM = txtM.TextstrM = txtM.Text ‘ strM = “5”‘ strM = “5”lstAnswer.ClearlstAnswer.Clear ‘ list box is cleared‘ list box is cleared

’ ’ print the same thing 4 times, i.e. strMprint the same thing 4 times, i.e. strMFor j = 1 To 4For j = 1 To 4 ‘ iterate 4 times, print same:‘ iterate 4 times, print same:

lstAnswer.AddItem( strM )lstAnswer.AddItem( strM )NextNext

Prints, for strM = “5”Prints, for strM = “5”55555 5 55

10

11

Another Simple For Next Loop

lstAnswer.ClearlstAnswer.Clear‘ ‘ prints sequence 1..4prints sequence 1..4‘ ‘ with implied carriage-return after each:with implied carriage-return after each:For j = 1 To 4For j = 1 To 4

lstAnswer.AddItem( CStr( j ) ) ‘ convert intlstAnswer.AddItem( CStr( j ) ) ‘ convert intNextNext

Prints 4 lines:Prints 4 lines:11223344

11

12

For Next Multiplication Table‘ ‘ see line continuation _ in samples:see line continuation _ in samples:‘ ‘ other line continations after , ( and before )other line continations after , ( and before )numM = CInt( txtM.Text )numM = CInt( txtM.Text )strM = txtM.TextstrM = txtM.TextlstAnswer.ClearlstAnswer.ClearFor j = 1 To 10For j = 1 To 10

lstAnswer.AddItem(strM & “ x “ & CStr(j) & “ = “ & _lstAnswer.AddItem(strM & “ x “ & CStr(j) & “ = “ & _CStr( numM * j ) )CStr( numM * j ) )

NextNext

Prints, for numM = 5Prints, for numM = 55 x 1 = 55 x 1 = 55 x 2 = 10 5 x 2 = 10 . . .. . .5 x 10 = 50 5 x 10 = 50

12

13

Do While Concept

• Sometimes we can’t tell in advance how many times a Sometimes we can’t tell in advance how many times a loop iteratesloop iterates

• Or, it might just be clearer to use a logic that checks Or, it might just be clearer to use a logic that checks as we go alongas we go along

• In that case we can use a In that case we can use a Do While Do While loop instead of a loop instead of a For Next For Next looploop

13

14

Do While ExampleUse Use For Next For Next loop program, but this time with a loop program, but this time with a Do While Do While looploop

numM = CInt(txtM.Text)numM = CInt(txtM.Text)strM = txtM.TextstrM = txtM.TextlstAnswer.ClearlstAnswer.Clear

j = 1 ‘ set j to initial value 1 at loop startj = 1 ‘ set j to initial value 1 at loop startDo While j <= 12Do While j <= 12 ‘ upper bund is constant‘ upper bund is constant

lstAnswer.AddItem( strM & “ x “ & CStr(j) & “ = “ & _lstAnswer.AddItem( strM & “ x “ & CStr(j) & “ = “ & _CStr( numM * j ) )CStr( numM * j ) )

j = j + 1j = j + 1 ‘ this line makes the loop stop‘ this line makes the loop stopLoop Loop ‘ end with Loop instead of Next‘ end with Loop instead of Next

14

15

Do While Example

Here’s the numM by numM versionHere’s the numM by numM version

numM = CInt(txtM.Text)numM = CInt(txtM.Text) ‘ numM is an integer type‘ numM is an integer typestrM = txtM.TextstrM = txtM.Text ‘ strM ix a string type‘ strM ix a string typelstAnswer.ClearlstAnswer.Clearj = 1j = 1Do While j <= numMDo While j <= numM ‘ upper bound is variable‘ upper bound is variable

lstAnswer.AddItem( strM & “ x “ & CStr( j ) & “ = “ _lstAnswer.AddItem( strM & “ x “ & CStr( j ) & “ = “ _& CStr( numM * j ) )& CStr( numM * j ) )

j = j + 1j = j + 1LoopLoop

What happens if numM = 0?What happens if numM = 0?

15

16

Do While Loop Flowchart

Do While Do While conditioncondition

statementsstatements

including nested Do including nested Do WhileWhile

LoopLoop

Loop statements can Loop statements can execute foreverexecute forever

Condition true?

Execute statements within the loop.

Execute statementsthat follow the loop.

No

Yes

16

17

The Do Until Variation

Instead of repeating Instead of repeating WhileWhile a condition is true, we can a condition is true, we can repeat repeat UntilUntil the condition becomes true the condition becomes true

For example:For example:

Do While Do While varA <= 5varA <= 5

Is almost equivalent to:Is almost equivalent to:

Do Until Do Until varA > 5varA > 5

17

18

Test at the End Variation

• Instead of testing at the beginning of the loop, we can Instead of testing at the beginning of the loop, we can test at the endtest at the end

• This is useful because, many times, we want to do the This is useful because, many times, we want to do the loop code at least once, no matter what!loop code at least once, no matter what!

18

19

Do Until ExampleMultiplication example using Multiplication example using Do Until Do Until loop with test at the endloop with test at the end

numM = CInt( txtM.Text )numM = CInt( txtM.Text )

strM = txtM.TextstrM = txtM.Text

lstAnswer.ClearlstAnswer.Clear

j = 1j = 1

Do Do

lstAnswer.AddItem(strM & “ x “ & CStr(j) & “ = “ & CStr(numM * j))lstAnswer.AddItem(strM & “ x “ & CStr(j) & “ = “ & CStr(numM * j))

j = j + 1 j = j + 1

Loop Until j > 12Loop Until j > 12

19

20

Do Loop Flowchart (Until, test at end)

DoDo

statement(s)statement(s)

Loop Until Loop Until conditioncondition

Do Loop statements Do Loop statements always run at least oncealways run at least once

Condition true?

Execute statements within the loop

Execute statementsthat follow the loop

No

Yes

20

21

Nested Loops

• Remember how Remember how IfIf statements can be “nested”: you statements can be “nested”: you can have an can have an IfIf inside another inside another IfIf

• We can also put whatever we want inside a loop, We can also put whatever we want inside a loop, including another loopincluding another loop

• If we do this, the inner loop is executed completely, If we do this, the inner loop is executed completely, for all of its repetitions, each time the outer loop is for all of its repetitions, each time the outer loop is executed onceexecuted once

21

22

Nested LoopsDim j, k As IntegerDim j, k As Integer

lstAnswer.ClearlstAnswer.Clear

For j = 1 To 12For j = 1 To 12

For k = 1 To 4For k = 1 To 4

lstAnswer.AddItem(“j = “ & CStr( j ) & “ k= “ & lstAnswer.AddItem(“j = “ & CStr( j ) & “ k= “ & CStr( k ) )CStr( k ) )

Next ‘ kNext ‘ k

Next ‘ jNext ‘ j

‘ ‘ how many lines of output??how many lines of output??

22

23

Output of Nested Loop

j = 1 k = 1j = 1 k = 1

j = 1 k = 2j = 1 k = 2

j = 1 k = 3j = 1 k = 3

j = 1 k = 4j = 1 k = 4

j = 2 k = 1j = 2 k = 1

j = 2 k = 2j = 2 k = 2

j = 2 k = 3j = 2 k = 3

j = 2 k = 4j = 2 k = 4

j = 3 k = 1j = 3 k = 1

Etc.Etc.

23

24

Another Nested Loop

Dim j, k As IntegerDim j, k As Integer

lstAnswer.ClearlstAnswer.Clear

For j = 1 To 12For j = 1 To 12

For k = 1 To 4For k = 1 To 4

lstAnswer.AddItem(“j = “ & CStr( j ) & “ k= “ & CStr( k lstAnswer.AddItem(“j = “ & CStr( j ) & “ k= “ & CStr( k ) )) )

Next ‘kNext ‘k

lstAnswer.AddItem(“Finished j = “ & CStr( j ) )lstAnswer.AddItem(“Finished j = “ & CStr( j ) )

Next ‘jNext ‘j

24

25

Results of Another Nested Loopj = 1 k = 1j = 1 k = 1

j = 1 k = 2j = 1 k = 2

j = 1 k = 3j = 1 k = 3

j = 1 k = 4j = 1 k = 4

Finished j = 1Finished j = 1

j = 2 k = 1j = 2 k = 1

j = 2 k = 2j = 2 k = 2

j = 2 k = 3j = 2 k = 3

j = 2 k = 4j = 2 k = 4

Finished j = 2Finished j = 2

j = 3 k = 1j = 3 k = 1

Etc.Etc.

25