|
1
|
- While (do…while)
Statement
- For Statement
|
|
2
|
- Loop (Repetition) statements control a block (=paragraph) of code to be
executed for a fixed number of times or until a certain condition is
met.
- Managed loop: Count-controlled loop(repetitions) terminate the execution
of the block after it is executed for a fixed number of times.
- Unmanaged loop: Sentinel-controlled loop(repetitions) terminate the
execution of the block after one of the designated values called a
sentinel is encountered.
|
|
3
|
|
|
4
|
|
|
5
|
|
|
6
|
|
|
7
|
|
|
8
|
|
|
9
|
- Watch out for the off-by-one error (OBOE).
- Make sure the loop body contains a statement that will eventually cause
the loop to terminate.
- Make sure the loop repeats exactly the correct number of times.
- If you want to execute the loop body N times, then initialize the
counter to 0 and use the test condition counter < N or initialize the
counter to 1 and use the test condition counter <= N.
|
|
10
|
|
|
11
|
- An infinite loop often results in an overflow error.
- An overflow error occurs when you attempt to assign a value larger than
the maximum value the variable can hold.
- In Java, an overflow does not cause program termination. With types float
and double, a value that represents infinity is assigned to the
variable. With type int, the value “wraps around” and
becomes a negative value.
|
|
12
|
|
|
13
|
|
|
14
|
- Goal: Execute the loop body 10 times.
|
|
15
|
|
|
16
|
|
|
17
|
|
|
18
|
- Loop-and-a-half repetition control can be used to test a loop’s
terminating condition in the middle of the loop body.
- It is implemented by using reserved words while, if, and break.
|
|
19
|
|
|
20
|
- Be aware of two concerns when using the loop-and-a-half control:
- The danger of an infinite loop. The boolean expression of the while statement
is true, which will always evaluate to true. If we forget to include an
if statement to break out of the loop, it will result in an infinite
loop.
- Multiple exit points. It is possible, although complex, to write a
correct control loop with multiple exit points (breaks). It is good
practice to enforce the one-entry one-exit control flow.
|
|
21
|
- A confirmation dialog can be used to prompt the user to determine
whether to continue a repetition or not.
|
|
22
|
|
|
23
|
|
|
24
|
|
|
25
|
|
|
26
|
|
|
27
|
- Nesting a for statement inside another for statement is commonly used
technique in programming.
- Let’s generate the following table using nested-for statement.
|
|
28
|
|