Transcript Chapter 1

Chapter 8: Statement-Level
Control Structures
•
•
•
•
•
Introduction
Selection Statements
Iterative Statements
Unconditional Branching
Invariants (Ch 3.5.2)
8-1
Control Statements: Evolution
• Control statements
– Statements that select or repeat control flow
– Statements in FORTRAN I were based directly on
IBM 704 hardware
• Much research and argument in the 1960s
about the issue
– One important result: It was proven that all
algorithms represented by flowcharts can be
coded with only two-way selection and pretest
logical loops, without needing “goto”
8-2
Control Structure
• A control structure is a control statement and the
statements whose execution it controls
• Design question
– Should a control structure have multiple entries? Or
allowing “goto”?
• Structured programming:
– The structure of the program text should help us
understand what the program does.
– The flow of control through the program is evident from
the syntactic structure of the program text, i.e., singleentry/single-exit.
8-3
Selection Statements
• A selection statement provides the means of
choosing between two or more paths of execution
• Two-way selectors
– General form:
if control_expression
then clause
else clause
– ALGOL 60:
if (boolean_expr)
then statement (then clause)
else statement (else clause)
The statements could be single or compound
8-4
Nesting Selectors
• Java example
if (sum == 0)
if (count == 0)
result = 0;
else result = 1;
• Which if gets the else?
• static semantics rule in Java, C, C++, and C# : else matches
with the nearest if
• To force an alternative semantics, compound statements may
be used:
if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;
• Perl requires that all then and else clauses to be compound
8-5
Multiple-Way Selection Statements
•
•
•
Allow the selection of one of any number of statements or
statement groups
C’s switch statement
switch (expression) {
case const_expr_1: stmt_1;
…
case const_expr_n: stmt_n;
[default: stmt_n+1]
}
Example
Switch (index) {
case 1:
case 3: odd += 1; sumodd += index; break;
case 2:
case 4: even += 1; sumeven += index; break;
}
8-6
Multiple-Way Selection: C
•
Design choices for C’s switch statement
1. Control expression can be only an integer type
2. Selectable segments can be statement sequences,
blocks, or compound statements
3. Any number of segments can be executed in one
execution of the construct (there is no implicit
branch at the end of selectable segments)
4. default clause is for unrepresented values (if
there is no default, the whole statement does
nothing)
8-7
Multiple-Way Selection: Ada
• The Ada case statement
case expression is
when choice list => stmt_sequence;
…
when choice list => stmt_sequence;
[when others => stmt_sequence;]
end case;
• More reliable than C’s switch (once a
stmt_sequence execution is completed, control is
passed to the first statement after the case
statement
8-8
Multiple-Way Selection Using if
• Multiple Selectors can appear as direct
extensions to two-way selectors, using
else-if clauses, for example in Ada:
if ...
then ...
elsif ...
then ...
elsif ...
then ...
else ...
end if
8-9
Iterative Statements
• The repeated execution of a statement or
compound statement is accomplished
either by iteration or recursion
• General design issues for iteration control
statements:
1. How is iteration controlled?
2. Where is the control mechanism in the loop?
8-10
Counter-Controlled Loops
•
•
A counting iterative statement has a loop variable,
and a means of specifying the loop parameters
(initial, terminal, and stepsize values)
Design Issues:
1. What are the type and scope of the loop variable?
2. What is the value of the loop variable at loop termination?
3. Should it be legal for the loop variable or loop
parameters to be changed in the loop body, and if so,
does the change affect loop control?
4. Should the loop parameters be evaluated only once, or
once for every iteration?
8-11
Counter-Controlled Loops: FORTRAN
• FORTRAN 90 syntax
DO label var = start, finish [, stepsize]
• Example:
Do 10 Index = 1, 10
...
10 Continue
• Stepsize can be any value but zero
• Parameters can be expressions
• Design choices:
1. Loop variable must be INTEGER
2. Loop variable always has its last value
3. The loop variable cannot be changed in the loop, but the
parameters can; because they are evaluated only once, it does
not affect loop control
4. Loop parameters are evaluated only once
8-12
Counter-Controlled Loops: Pascal
•
Pascal’s for statement
for variable := initial (to|downto) final do
statement
•
Example
for i := 1 to 5 do A[i] := 0
•
Design choices:
1. Loop variable must be an ordinal type of usual scope
2. After normal termination, loop variable is undefined
3. The loop variable cannot be changed in the loop; the
loop parameters can be changed, but they are evaluated
just once, so it does not affect loop control
4. Loop parameters are evaluated Just once
8-13
Counter-Controlled Loops: C
• C’s for statement
for ([expr_1] ; [expr_2] ; [expr_3]) statement
• Example:
For (count = 1; count <= 10; count++) {…}
• The expressions are usually statements, or even statement
sequences, with the statements separated by commas
– The value of a multiple-statement expression is the value of the
last statement in the expression
• There is no explicit loop variable
• Everything can be changed in the loop
• The first expression is evaluated once before the loop entry ,
but the other two are evaluated with each iteration
– expr_2: condition for staying within the loop
– expr_3: evaluated before every next iteration
– missing expr_2 is true.
8-14
Counter-Controlled Loops: C++
• C++ differs from C in two ways:
1. The control expression can also be Boolean
2. The initial expression can include variable
definitions (scope is from the definition to the
end of the loop body)
• Example:
For (int count = 1; count <= 10; count++)
{…}
• Java and C#
– Differs from C++ in that the control
expression must be Boolean
8-15
Logically-Controlled Loops
•
•
Repetition control is based on a Boolean
Design issues:
–
•
Pre-test or post-test?
General forms:
while (ctrl_expr)
loop body
•
do
loop body
while (ctrl_expr)
C and C++ also have both, but the control
expression for the post-test version is treated
just like in the pre-test case (while-do and dowhile)
8-16
Logically-Controlled Loops: Pascal
•
•
Pascal has separate pre-test and post-test logical loop
statements (while-do and repeat-until)
Example of remove adjacent duplicates:
1, 1, 2, 2, 2, 3, 1, 4, 4 -> 1, 2, 3, 1, 4
program uniq (input, output);
var x, next: integer;
begin
read(x);
while x <> 0 do begin
writeln(x);
repeat read(next); until next <> x;
x := next;
end;
end.
8-17
User-Located Loop Control Mechanisms
•
•
Sometimes it is convenient for the programmers
to decide a location for loop control (other than
top or bottom of the loop)
The break statement
–
–
•
C , C++: sends control out of the enclosing loop to the
statement following the loop; for any loop or switch;
one level only for nested loops
Java and C#: a labeled break statement; send control
out of the labeled loop
The continue statement
–
C, C++, Phthon: it skips the remainder of this iteration,
but does not exit the loop
8-18
Examples of break and continue
• Java
outerLoop:
for (row = 0; row < numRows; row++)
for (col = 0; col < numCols; col++) {
sum += mat[row][col];
if (sum > 1000.0)
break outerLoop;
}
• C
while (sum < 1000) {
getnext(value);
if (value < 0) continue;
sum += value;
}
8-19
Examples of break and continue
(cont)
• The following program fragment skips over
consecutive blank, tab, and newline characters,
and keeps track of line numbers when
encountering a newline character.
for ( ; ; c= getchar( ) ) {
if ( c == ‘ ‘ | | c == `\t`)
continue;
if ( c ! = ‘\n’ )
break;
++lineno;
}
8-20
Iteration Based on Data Structures
• Number of elements of in a data structure control
loop iteration
• Control mechanism is a call to an iterator function
that returns the next element in some chosen
order, if there is one; else loop is terminate
• C#’s foreach statement iterates on the elements of
arrays and other collections:
Strings[] strList = {“Bob”, “Carol”, “Ted”};
foreach (Strings name in strList)
Console.WriteLine (“Name: {0}”, name);
• The notation {0} indicates the position in the string
to be displayed
8-21
Unconditional Branching
• Transfers execution control to a specified
place in the program
• Well-known mechanism: goto statement
• Represented one of the most heated debates
in 1960’s and 1970’s
• Major concern: Readability
• Some languages do not support goto
statement (e.g., Module-2 and Java)
• C# offers goto statement (can be used in
switch statements)
8-22
Syntax of statements in C
8-23
Invariants
• An assertion is a true/false condition about the
state of a computation, e.g., x > y.
• An invariant at some point in a program is an
assertion that holds whenever the point is reached
at run time.
• Correctness is a property of dynamic computation.
Invariants are a bridge between the static program
text and the dynamic progress of a computation.
• It is best to start with invariants and use them to
design the program.
• Invariants will be enclosed with braces { and }.
8-24
Examples of invariants
Example:
while x >= y do
{ x >= y if we get here }
x := x -y
Example:
{ x >= 0 and y > 0 }
while x > = y do
{ y > 0 and x > = y }
x: = x - y
{ x > = 0 and y > 0 }
8-25
Precondition and Postcondition
• precondition: an assertion before a statement.
– states the relationships and constraints among variables
that are true at that point in execution
• postcondition: an assertion after a statement
They play the following roles with while loops:
• precondition: captures the conditions for
executing the loop.
• loop invariant: captures the condition for staying
within the loop.
• postcondition: captures the condition upon leaving
the loop.
8-26
Invariants: Program Design (in Pascal)
Example: programs to remove adjacent duplicates
e.g., 11
222 3 1 44 =>
(run)
1 2 3 1 4
read ( x );
while x is not the end marker do begin
{here, x is the first element of a run}
writeln ( x );
repeat read ( next ) until next ≠ x;
{here, we have read one element too many}
x := next;
end
8-27
Program Proof Process
• A weakest precondition is the least restrictive
precondition that will guarantee the postcondition
• An example
– a = b + 1 {a > 1}
– One possible precondition: {b > 10}
– Weakest precondition:
{b > 0}
• The postcondition for the entire program is the
desired result
– Work back through the program to the first statement. If
the precondition on the first statement is the same as the
program specification, the program is correct.
8-28