problem solving with loops
DESCRIPTION
Problem Solving with Loops. Lesson 7. Overview. Flowchart Symbols The Loop Logic Structure Incrementing/ Decrementing Accumulating While/ EndWhile Repeat/Until. Automatic-Counter Loop (For) Nested Loops Indicators Algorithm Instructions Recursion. Flowchart Symbols. Decision - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/1.jpg)
COP1000 1
Problem Solving with Loops
Lesson 7
McManus
![Page 2: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/2.jpg)
COP1000 2
Overview• Flowchart Symbols • The Loop Logic
Structure• Incrementing/
Decrementing• Accumulating• While/EndWhile• Do Until/Loop
• Repeat/Until• Automatic-
Counter Loop (For)• Nested Loops• Indicators• Algorithm
Instructions • Recursion
McManus
![Page 3: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/3.jpg)
COP1000 3
Flowchart Symbols• Decision
– True/False/Else• Process• Assign
McManus
Assign
Process
Decision
![Page 4: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/4.jpg)
COP1000 4
Repetition Structure Logic• Allows the programmer to specify that an
action is to be repeated based on the truth or falsity of some condition.
• Otherwise known as iteration.• Two types of Iteration
– Definite– Indefinite
McManus
![Page 5: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/5.jpg)
COP1000 5
Definite Repetition• Known as definite because the
number of iterations to be performed at runtime is known.
• Also known as Counter-controlled Repetition – Uses a variable called a counter to
control the number of times a set of statements should execute.
McManus
![Page 6: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/6.jpg)
COP1000 6
Definite ExampleWhile Count < 3
Total = Total + GradeCount = Count + 1
End While
As long as the value in Count is less than 3, the loop will continue to process.
PseudocodeMcManus
![Page 7: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/7.jpg)
COP1000 7
Indefinite Repetition• Known as indefinite because the number
of iterations at runtime is not known before the loop begins executing.– Uses a sentinel value (signal value, a flag
value, or a dummy value) to indicate “end of data entry.”• When using a sentinel
– Choose a sentinel that will not naturally exist within the range of data being used.
– Ex. 999-99-9999 for Social Security Numbers
McManus
![Page 8: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/8.jpg)
COP1000 8
Indefinite ExampleWhile TimeCard.SSN <> Sentinel
Obtain time from each card Calculate pay
End While
As long as there are items still remaining on the list the loop will continue.
Pseudocode
McManus
![Page 9: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/9.jpg)
COP1000 9
The Looping Logic Structure
• Is one of the three types of program control structures – Sequence– Selection (Decision)– Repetition (Looping or Iteration)
McManus
![Page 10: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/10.jpg)
COP1000 10
The Looping Process• Is made up of:
– Initialization– Condition (the test)– Increment (or Decrement)
• The Accumulator, although used in frequently in loops, is NOT part of the looping process
McManus
This is a Test
Question!!!
![Page 11: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/11.jpg)
COP1000 11
Looping Process• The Initialization• set to an initial value
– usually zero but not all the time• Examples:
– Count = 0 – Count = 1– Count = 100
McManus
![Page 12: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/12.jpg)
COP1000 12
Looping Process• The Test or Condition
– tested before the start of each loop repetition, called the iteration or pass.
• Examples:– Count < 3 Count = 10– Count <= 3 Count <> 10– Count > 5– Count >= 5
McManus
![Page 13: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/13.jpg)
COP1000 13
Looping Process• The Increment (or Decrement)
– updates the variable during each iteration
– must be part of the loop body (usually the last line)
• Examples:– Count = Count + 1 increment– Count = Count – 1 decrement
McManus
![Page 14: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/14.jpg)
COP1000 14
The Accumulator• Variables used to store values being
computed in increments during the execution of a loop.
• Not part of the Looping Process– But quite often an integral addition to the process– Very often looks like an increment, which is part of the
looping process• Examples:
– Sum = Sum + 1– TotalGrade = TotalGrade + CurrentGrade
McManus
![Page 15: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/15.jpg)
COP1000 15
Common Forms of Loops• The Three Most Common Loop-
control statements: – Pretest Loops:
• the While/End While, • the Do Until/Loop,• the For/Next, and
– Posttest Loops:• the Repeat/Until
McManus
There are lots of other loop variations dependent on the language.
![Page 16: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/16.jpg)
COP1000 16
While/End While • The While/End While statement
– The most versatile of the loops• Can be used for both definite and indefinite
loops– The loop body contains the instructions
to be repeated.– The loop-repetition condition is the
Boolean expression after the reserved word while which is evaluated before each repetition of the loop body.
McManus
![Page 17: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/17.jpg)
COP1000 17
While StructureSet counter To 0While counter < final_value
statementsIncrement counter by 1
End While
McManus
?
Init
Stmt
true
false
Stmt
Pseudocode Example
![Page 18: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/18.jpg)
COP1000 18
Three Examples
Using Different Languages
McManus
![Page 19: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/19.jpg)
COP1000 19
While ExampleX := 3; How many times does theCount := 0; loop execute?while Count < 3 do begin What is displayed? X := X * 2; 6 Print (X); 12 Count := Count + 1 24 end; {while Count}
Pascal Code Example
McManus
![Page 20: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/20.jpg)
COP1000 20
Another While ExampleDim X as IntegerDim Count as IntegerX = 3Count = 0While Count < 3 X = X * 2 Print X Count = Count + 1End While
VB Code ExampleMcManus
![Page 21: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/21.jpg)
COP1000 21
Another While Exampleint X = 3;int Count = 0;While (Count < 3)
{ X = X * 2; cout << X << endl; Print statement Count = Count + 1;}
C++ Code Example
McManus
![Page 22: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/22.jpg)
COP1000 22
Looping Examples• Two computer language examples:
McManus
BASIC C++WHILE condition InstructionsEND WHILE
while (condition) { Instructions }
FOR i = Start TO End InstructionsNEXT i
for (initial; conditional; incr) { Instructions }
![Page 23: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/23.jpg)
COP1000 23
Indefinite Examples• A Sentinel-Controlled Loop
–Controlled by a sentinel value.–Examples
end-of-file marker (EOF)end-of-line marker (EOL)999999999 for SSN 999999 for date**
**Be careful with this one!
McManus
![Page 24: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/24.jpg)
COP1000 24
Indefinite Examples• A Sentinel-Controlled Loop
Pseudocode TemplateInitialize Sum to 0 Read the first value into counter variable While counter variable is not sentinel do
Add counter variable to SumRead next value into counter variable
End While;
McManus
![Page 25: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/25.jpg)
COP1000 25
Another Indefinite Example
• Boolean Flag-Controlled Loops– Executes until the event being
monitored occurs. • A program flag, or flag, is a Boolean variable
whole value (True or False) signals whether a particular event occurs.
• The flag should initially be set to False and reset to True when the event occurs.
• Primarily used when interfacing with devices.
McManus
![Page 26: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/26.jpg)
COP1000 26
Another Indefinite Example
• Boolean Flag-Controlled Loops–Pseudocode TemplateInitialize flag to FalseWhile Not flag (While Not False
statements.. Reset flag to True if the event being monitored
occursEnd While; {while}
McManus
![Page 27: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/27.jpg)
COP1000 27
Do/Until• Logical Opposite of
the While Loop• Unlike the
While/While-End, the Do/Until tests for falsity.– Should be used when
the question being asked is
more naturally asked in the negative.
McManus
Counter < 5
Init
Stmt
false
true
Stmt
![Page 28: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/28.jpg)
COP1000 28
Do/Until Examplex = 3Count = 3Do Until Count < 1 X = X * 2 Print X Count = Count – 1 ‘DecrementLoop
VB CodeMcManus
![Page 29: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/29.jpg)
COP1000 29
Repeat/Until Structure• Similar to the While/While-End
structure, except:– In the While Loop
• loop-continuation is tested at the beginning of the loop before the body of the loop is performed.
– In the Repeat/Until Loop• loop-continuation is tested after the loop
body is performed, thus executing the loop body at least once.
McManus
![Page 30: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/30.jpg)
COP1000 30
Repeat Until Loop• Pseudocode Template
Repeatstatementsincrement counterVariable
Until testCondition• Notice that the
statements are executed before thecondition to end the loop
McManus
counter = 1
counter < 5
True
False
statements
ActionoccursbeforeTest
![Page 31: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/31.jpg)
COP1000 31
The For/Next Loop• Combines all of the Loop Process
components into one statement.• Notes on the Counter:
– Can be used non-destructively but must not be modified (destructively) within the loop body.
– Should be a local variable.• The loop body will not be executed if initial
is greater than the final value, unless the increment value is negative.
McManus
![Page 32: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/32.jpg)
COP1000 32
The For/Next Loop• Pseudocode Example
For counter = initialvalue To finalvalue Step 1statements… ‘to increment
Next counter
For counter = finalvalue To initialvalue Step -1statements… ‘to decrement
Next counter
McManus
![Page 33: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/33.jpg)
COP1000 33
For Loop Flowchart• Note that the “To” is equivalent
to “while less than or equal to”
McManus
counter = 1
Print counter counter = counter + 1
counter <= 5
True
False
(implicit) (implicit)
(explicit)
For counter = 1 to 5 Step 1 Print counter Next counter
![Page 34: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/34.jpg)
COP1000 34
Nested Loops• Loops can be nested just as IF
statements.– Cannot use the same counter-control
variable for the inner loop as is used for the outer loop.
McManus
x yTrue
False False
True
![Page 35: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/35.jpg)
COP1000 35
Nested Loop TemplateInitialize outer loopWhile outer loop test {while}
statements...
Initialize inner loop While inner loop test {while} Inner loop processing and Update inner loop variable
End While {inner while}
statements... Update outer loop variable
End While {outer while}McManus
Pseudocode Example
![Page 36: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/36.jpg)
COP1000 36
Nested Loop Code Example
Dim outercounter As IntegerDim innercounter As Integeroutercounter = 1
While outercounter <= 3innercounter = 1
While innercounter <= 3 innercounter = innercounter + 1End While ‘innercounter
outercounter = outercounter + 1
End While ‘outercounterMcManus
VB Code
![Page 37: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/37.jpg)
COP1000 37
Nested Loop Code Example
Dim OC As IntegerDim IC As IntegerOC= 1 While OC <= 3
Print OCIC = 1While IC<= 3Print IC IC = IC+ 1End While ‘ICOC = OC + 1
End While ‘OCVB Code
McManus
OC IC
True
False False
True Print ICPrint OC
Outercounter = OCInnercounter = IC
![Page 38: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/38.jpg)
COP1000 38
Loop Invariants• Are statements of the loop’s eventual
goal– Assertions about the characteristics of a
loop that always must be true for a loop to execute properly.
– The assertions are true on loop entry, at the start of each loop iteration, and on exit from the loop.
– They are not necessarily true at each point within the body of the loop.
McManus
![Page 39: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/39.jpg)
COP1000 39
Four Special Cases of Loops
• When the loop is skipped entirely (zero iteration loop)
Ex. If Balance <> -100Write Check
End If ???• When the loop body is executed just
once• When the loop executes some
normal number of times• When the loop fails to exit (infinite
loop)McManus
![Page 40: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/40.jpg)
COP1000 40
Watch out for…• Beware of infinite loops• Beware of off-by-one Loop Errors
– These will cause a logic error, but not a run-time error• Executes the loop one too many times• Executes the loop one too few times
McManus
![Page 41: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/41.jpg)
COP1000 41
Loop Testing Strategy• Verify the Algorithm
– Test the value of the algorithm • before the loop• during the loop, and • after the loop.
McManus
![Page 42: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/42.jpg)
COP1000 42
Recursion
Or a case of twisted tails
McManus
![Page 43: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/43.jpg)
COP1000 43
Recursion• Is used in computer science and software
engineering as a:– Means of describing, defining, or specifying
things– Means of designing solutions to problems
(using divide & conquer)
McManus
More info in Notes Section
![Page 44: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/44.jpg)
COP1000 44
Recursion• Occurs when a function calls itself from
within the body of the function• Also known as “procedural iteration”• Classic Examples of Recursion
– Factorial– Fibonacci
McManus
![Page 45: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/45.jpg)
COP1000 45
Recursive Definitions• A recursive definition is one where
something is defined in terms of itself
• Almost all algorithms that require looping can be defined iteratively or recursively
• Requires two parts:– Base case (or stopping case)– Recursive step
McManus
More info in Notes Section
![Page 46: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/46.jpg)
COP1000 46
Factorial x!• How it works:
If X = 3, the chain of recursive calls would be as follows:
Factorial(3) 3 * Factorial(2) 3 * (2 * Factorial(1) )
Precondition x > 0Postcondition
Returns the product 1 * 2 * 3 * …* x for x > 1
Returns 1 when X is 0 or 1.
McManus
![Page 47: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/47.jpg)
COP1000 47
Breaking Recursion Down
McManus
Factorial(3) = 3 * Factorial(2)
Factorial(2) = 2 * Factorial(1)
Factorial(1) = 1 * 1 = 1Factorial(1) = 1 * Factorial(0)
Factorial(2) = 2 * 1 = 2
Factorial(3) = 3 * 2 = 6
Factorial(0) = 1
More info in Notes Section
![Page 48: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/48.jpg)
COP1000 48
VB Factorial ExamplePrivate Function Factorial(ByRef y As Double) _
As Double ‘2nd double defines Factorial If y <= 1 Then Factorial = 1 ' Base case Else Factorial = y * Factorial(y - 1) ' Recursive step End IfEnd FunctionThe Base Case is also known as the Stopping Case.
McManus
Call Pop5 1204 243 62 21
More info in Notes Section
![Page 49: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/49.jpg)
COP1000 49
The Original Fibonacci Problem
• Investigated (in the year 1202) was about how fast rabbits could breed in ideal circumstances.
• Suppose a newly-born pair of rabbits, one male, one female, are put in a field. Rabbits are able to mate at the age of one month so that at the end of its second month a female can produce another pair of rabbits. Suppose that our rabbits never die and that the female always produces one new pair (one male, one female) every month from the second month on.
• The puzzle that Fibonacci posed was...
• How many pairs will there be in one year?
• At the end of the first month, they mate, but there is still one only 1 pair.
• At the end of the second month the female produces a new pair, so now there are 2 pairs of rabbits in the field.
• At the end of the third month, the original female produces a second pair, making 3 pairs.
• At the end of the fourth month, the original female has produced yet another new pair, the female born two months ago produces her first pair also, making 5 pairs.
McManus
![Page 50: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/50.jpg)
COP1000 50
Fibonacci Tree of Rabbits
McManus
FemaleMale
More info in Notes Section
![Page 51: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/51.jpg)
Fibonacci Curve or Golden Spiral
• We can make another picture showing the Fibonacci numbers 1,1,2,3,5,8,13
• If we start with two small squares of size 1 next to each other.
• On top of both of these draw a square of size 2 (=1+1).
McManus COP1000 51
![Page 52: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/52.jpg)
COP1000 52
Golden Rectangle & Golden Spiral
• Corners of the Golden Rectangle are joined to form a Golden Spiral, which gets 1.6180339887 times wider with each 90 turn.
• The Spiral occurs frequently in Nature!
McManus
![Page 53: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/53.jpg)
COP1000 53
The Fibonacci Sequence• The number of clockwise spirals and
the number of counterclockwise spirals formed by the seeds of certain varieties of flowers
McManus
![Page 54: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/54.jpg)
COP1000 54
Sunflower Spirals
McManus
![Page 55: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/55.jpg)
COP1000 55
Fibonacci Sequence• Fibonacci Numbers
Each Fibonacci number is the sum of the two preceding Fibonacci numbers. • The Fibonacci series defined recursively:
Fibonacci(0) = 0Fibonacci(1) = 1Fibonacci(2) = 1Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n - 2)
McManus
A Shortened Form:Fib (1) = 1 Fib (2) = 1Fib (n) = Fib (n - 1) + Fib (n - 2)
Fib(3) = Fib(2) + Fib(1) = 1 + 1 = 2Fib(4) = Fib(3) + Fib(2) = 2 + 1 = 3Fib(5) = Fib(4) + Fib(3) = 3 + 2 = 5Fib(6) = Fib(5) + Fib(4) = 5 + 3 = 8
![Page 56: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/56.jpg)
COP1000 56
Golden Ratio• Is an Irrational Number• 1.618039887• Symbol: • Also: • Used in Stock Market manipulations • Used in Nature
McManus
![Page 57: Problem Solving with Loops](https://reader035.vdocument.in/reader035/viewer/2022062520/56816022550346895dcf25a7/html5/thumbnails/57.jpg)
COP1000 57
Next?
McManus