cs 106 computing fundamentals ii chapter 61 “ loops ”

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

Upload: mieko

Post on 12-Jan-2016

28 views

Category:

Documents


1 download

DESCRIPTION

Herbert G. Mayer, PSU CS Status 7/29/2013 Initial content copied verbatim from CS 106 material developed by CS professors: Cynthia Brown & Robert Martin. CS 106 Computing Fundamentals II Chapter 61 “ Loops ”. Syllabus. Repetition Real-Life Examples Multiplication Table Example - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 2: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 3: CS 106 Computing Fundamentals II Chapter 61 “ 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

Page 4: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 5: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

5

Multiplication Table Example

5

Page 6: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 7: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 8: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 9: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 10: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 11: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 12: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 13: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 14: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 15: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 16: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 17: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 18: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 19: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 20: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 21: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 22: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 23: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 24: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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

Page 25: CS 106 Computing Fundamentals II Chapter 61 “ Loops ”

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