01-11-2012, 02:13 PM
Repetition and Iteration
Repetition.ppt (Size: 61 KB / Downloads: 22)
Repetition
The development of thinking assistant machines was to relieve people from tedious tasks
The nature of computers & programs is well suited for repetition
Execute simple instructions quickly
Adding a sequence of numbers to a running total
Checking a data port for incoming data
While Loop Details
What is the minimum number of times the statements in the loop body may be executed?
What is the maximum number of times the statements in the loop body may be executed?
Notice that we have an initialization step
before the loop
Notice that we also have an increment step
in the loop
For Loop Details
What is the minimum number of times the statements in the loop body may be executed?
What is the maximum number of times the statements in the loop body may be executed?
Is there any relationship between the three control statements?
e.g., do they all need to refer to x?
Is an empty statement valid?
Is it valid as a for loop control statement?
Do While Loop Details
What is the minimum number of times the statements in the loop body may be executed?
What is the maximum number of times the statements in the loop body may be executed?
The braces are not strictly required
Haven't found a compiler that doesn't
Since most Java compilers use parts from C and C++ compilers, we end up using them in each language here
Loop Issues
Are infinite loops bad?
Only if that’s not what you intended
Loop Style
Use the correct loop for the task
Braces
Indentation
Loop Distinctions
While Loop
Test before body
Body may never execute
Do While Loop
Test after body
Body always executes once
For Loop
Has initialization and iteration components
Similar to the While loop
Behind the loop constructs
When the language gets translated from the Java Virtual Machine byte code into the instructions for the host we have something like:
test loop control condition
jump to end of loop label if condition warrants
loop statements
unconditional jump to loop test condition
end of loop label
Break & Continue
Break
Exit the current loop
Out one level if nested
Continue
Skip to the end of the current loop
Both of these should be avoided!
Can often be written out of a loop
Well designed loop control statements
Use of conditional statements