Chapter 7 Iteration Revisited
- Iteration = repetition - a basic control structure
- The for loop revisited
- can use list to control a for loop
- accumulator pattern
- Note: the questions 7.2a.1 and 7.2a.2 are premature, do them after you read the section on while statements. Also, 7.2a.2 has incorrect indentation and syntax for the print.
- The while Statement
- Sentinel Logic not in textbook!
- a pattern that works when dealing with input which
has a sentinel value
- sentinel value
- a special value chosen ahead of time
which indicates the end of the data
- can be -1, 0, 999, "stop", whatever you choose
- is NOT real data!
- do not want to process it like real data!
- the pattern
input into a variable (say, x)
while x is not the sentinel value
input into x
- a nice example: reading numbers and
calculating their average. The sentinel value is going to be the
initialize sum to 0.0
initialize count to 0
input data item as a string, xStr
while xStr is not empty
convert xStr to a number, x
add x to sum
add 1 to count
input next data item as a string, xStr
Output sum / count
- Nested loops
- Flags not in the textbook
- Read this
- a flag is a boolean variable
- has only values of True and False
- give it a name that means something, "hasError", "inOrder"
- what a flag means is up to you!
"A True value means a negative number has been seen"
"A False value means there was an error in the input"
"A True means the data was in order, a False means it was not"
- initialize the flag variable first (to True or False,
whatever makes sense)
- process the data as it needs to be done
- test data for whatever condition the flag is meant to
- set the flag if needed
- at the end of the data, test the flag to see what
- usually used in loops, always needs if statements
- The 3n+1 Sequence
- a sequence in mathematics
- start with a number
- if it is even, take half of it
- if it is odd, form the number 3*number + 1
- do this until you reach the value 1
- unpredictable when that will happen, or if it will
- perfect problem for a while loop
- Newton's Method
- remember the lab with this problem?
- it had a loop that printed out 20 approximations
of the sqrt function using Newton's method
- a while loop is better because it can stop as soon
as the approximates get "close enough" or when the approximations stop
- note that the loop is controlled by a comparison
of two floats (and two calculated floats at that!).
How could you improve the control of the loop?
- Algorithms Revisited
- algorithms can be expressed clearly enough that anyone,
even a machine, can do them
- a lot of things humans do (recognize faces,
understand language, walk over rough terrain, create new things, ...)
cannot be expressed by an algorithm
- Simple Tables
- use \t for tab, \n for newline, \\ for a slash
- "escaped" character
- 2-Dimensional Iteration: Image Processing