9/20/2015assoc. prof. stoyan bonev1 cos220 concepts of pls aubg, cos dept lecture 06 components of...
TRANSCRIPT
04/19/23 Assoc. Prof. Stoyan Bonev 1
COS220 Concepts of PLs AUBG, COS dept
Lecture 06
Components of Programming
Languages, Part III
Reference: R.Sebesta, Chapter 8
04/19/23 Assoc. Prof. Stoyan Bonev 2
Lecture Contents:
• StatementLevel Control Structures– Compound Statements– Selection Statements– Iterative Statements
• Guarded Commands (after E.Dijkstra)
04/19/23 Assoc. Prof. Stoyan Bonev 3
Levels of expressing execution sequence:
The flow of control, or execution sequence in a program can be examined in several levels:
• Low: flow of control within Expressions (operands, operators, precedence, associativity)
• High: flow of control among Program Units (the routines concept and program modules)
• Intermediate: flow of control among statements– Selection statements (one-way, two-way, n-way)– Iterative statements (counter and logically controlled)– Unconditional branch stmts (goto, break, continue)
04/19/23 Assoc. Prof. Stoyan Bonev 4
Control Statements
• Computations in PL are accomplished by evaluating expressions followed by assigning the resulting values to variables and function calls (linear algorithms).
• There are very few useful programs that consist entirely only of assignment statements and function call statements.
• At least two additional linguistic mechanisms are necessary to make programs flexible & powerful– The mechanism of selecting among alternative control flow
paths of statement execution (branched algorithms)– The mechanism of causing the repeated execution of certain
collection of statements (looped algorithms)
• These mechanisms are provided by control statements.
04/19/23 Assoc. Prof. Stoyan Bonev 5
Control Statements – structure and configuration
• A great deal of theoretical research & discussion was done in 1960s-70s. A primary conclusion was formed: Although a single control statement is obviously sufficient (unconditional branch – selectable goto) a PL that is designed to not include goto needs only a small number of different control statements. It was shown that algorithms that can be expressed by flowcharts can be coded in a PL with two only control statements:– one for choosing between two control flow paths and– one for logically controlled iterations
• An important result of this is that unconditional branch statements are superfluous – one of the Structured Programming topics.
04/19/23 Assoc. Prof. Stoyan Bonev 6
Ref. to Structured Programming
• Boehm/Jacopini, 1965/66, Comm of the ACM, “Flow Diagrams, Turing Machines, and Languages with Only Two Formulation Rules”
• Edsger Dijkstra, 1965, IFAC congress, “Programming Considered a Human Activity”
• Edsger Dijkstra, 1968, Comm of the ACM, “Goto Statement Considered Harmful”
04/19/23 Assoc. Prof. Stoyan Bonev 7
Structured Programming Topics
• Sequence, Selection and Pretest Logical Loops are absolutely required to express computation.
• Each Control Structure should have a single entry (no multiple entries).
• Each Control Structure should have a single exit (after G.Myers, but nowadays controversial).
• A control structure described – on next slide • Structured Programming is known as a gotoless
programming.
04/19/23 Assoc. Prof. Stoyan Bonev 8
Control Structure
• Definition: A Control Structure is a control statement and the collection of statements whose execution it (the control structure) controls.
• Typical control structures:– Compound statement
– Selection statement
– Iterative statement
– Program unit (routine, function, procedure, method)
04/19/23 Assoc. Prof. Stoyan Bonev 9
From Theory Towards Practice• Programmers don’t care about results of
theoretical research on control statements.• Programmers/Developers/ take care about
readability/writability of PL.• All popular PL provide more control statements
than the two that are minimally required. So, writability is enhanced by a larger number of control statements:– Various different versions of
selection/iteration statements
04/19/23 Assoc. Prof. Stoyan Bonev 10
Towards Practice
• Question: Which is the best (or optimal) collection of control statements of a PL to provide the required capabilities and the desired writability?
• Answer: The solution is a compromise of how much should a PL be expanded to increase its writability at the expense of its simplicity, size, and readability.
Compound statements
04/19/23 Assoc. Prof. Stoyan Bonev 12
Compound Statements• Method to form statement collections. CS allow a collection
of statements to abstract as a single statement. Algol Pascal C-like begin BEGIN {
stmt_1; stmt_1; stmt_1; . . . . . . . . .
stmt_n; stmt_n stmt_n; end END }
• If CS contains definition/declaration, it’s a block.Algol C-like,Perl,JavaScript,PHPbegin { integer index,count; int index,count; . . . . . . end }
04/19/23 Assoc. Prof. Stoyan Bonev 13
Compound Statements
• Syntax diagram illustrates compound statement. C-like
begin
stmt_1;
. . .
stmt_n;
End
<CS> ::= begin <stmt> { ; <stmt> }* end
04/19/23 Assoc. Prof. Stoyan Bonev 14
Compound Statements• Early versions made definitions to appear
in the block beginning only. No such a restriction now. The scope of the variables is from definition point to the end of block.
C-like PL{ . . . int a;
. . . float b; . . .
}
Selection statements
04/19/23 Assoc. Prof. Stoyan Bonev 16
Selection Statements
• A selection statement provides the means of choosing between two or more paths of execution in a program.
• Classification:– One-Way selection construct – Two-Way selection construct – N-Way (multiple) selection construct
04/19/23 Assoc. Prof. Stoyan Bonev 17
Selection
If/Then structure (single selection)
T
F
If/Then/Else structure (double selection)
TF
...
(multiple selection)
04/19/23 Assoc. Prof. Stoyan Bonev 18
One-Way & Two-Way Selector
• General Form:if control_expression | if control_expression
then_clause | then_clause | else_clause
• Design Issues:– Form and type of the expression that controls the selection– How are then_ and else_ clauses specified?– How should the meaning of nested selectors be specified?
04/19/23 Assoc. Prof. Stoyan Bonev 19
VBasic selection statements include
If condition Then
statement sequence
End If
If condition Then
statement sequence1
Else
statement sequence2
End If
04/19/23 Assoc. Prof. Stoyan Bonev 20
C/C++ selection statements include
if (expression)
statement sequence
if (expression)
statement sequence1
else
statement sequence2
04/19/23 Assoc. Prof. Stoyan Bonev 21
One-Way & Two-Way Selector
• Syntax diagram illustrates selector stmt
04/19/23 Assoc. Prof. Stoyan Bonev 22
One-Way & Two-Way Selector
• The Control Condition/Expression– To be in parentheses if then reserved word is not used– C89: arithmetic expression– C99, C++: arithmetic or Boolean expression– Ada, Java, C#: Boolean expression only
• The Clause Form– In most PL then_ and else_ clauses appear as either
single statements or compound statements– Perl: always as compound statements– Braces { … } used to form compound statements
04/19/23 Assoc. Prof. Stoyan Bonev 23
Nesting Selectors• The problem: when two-way selection constructs can be nested
if (sum == 0) if (count == 0) result = 0; else result = 1;
• This construct may be interpreted in two different ways, depending on whether the else clause matches the first or the second then clause
• In most PL (C, C++, C#, Java) static semantics specifies: the else clause is always paired with the nearest most recent unpaired then clause (above the else clause)
04/19/23 Assoc. Prof. Stoyan Bonev 24
Nesting Selectors
• Perl does not have the problem because it requires that all then and else clauses should be compound
if (sum == 0) if (count == 0) result = 0; else result = 1;
• The corresponding Perl text in two versions with no ambiguity:
if (sum == 0) { if (sum == 0) { if (count == 0) { if (count == 0) {
result = 0; result = 0; } }
} else { else { result = 1; result = 1; } }
}
04/19/23 Assoc. Prof. Stoyan Bonev 25
Multiple Selectors
• The multiple selection construct allows the selection of one of any number of statements or statement groups
• Design Issues:– Form and type of the expression that controls the
selection– How are the selectable segments specified?– Is execution flow restricted to include just a single
selectable segment?– How should unrepresented selector expression values
be handled, if at all?
04/19/23 Assoc. Prof. Stoyan Bonev 26
Multiple Selectors - Examples
• Early versions (Fortran)– Arithmetic IF
IF (<expression>) 10, 20, 30
– Computed GOTOGOTO (<lab1>,<lab2>, … <labn>), <expression>
04/19/23 Assoc. Prof. Stoyan Bonev 27
Multiple Selectors - Examples
Visual Basic
Select Case JobClassCase 1
Bonus = salary * 0.1Case 2
Bonus = salary * 0.09Case 3, 4
Bonus = salary * 0.075Case 5 To 8
Bonus = salary * 0.05Case Is > 8
Bonus = salary * 0.02Case Else
Bonus = 0End Select
04/19/23 Assoc. Prof. Stoyan Bonev 28
Multiple Selectors - Examples
• C, C++, Java switch (<expression>)
{
case <const_expression_1>: <statement_1>;
case <const_expression_2>: <statement_2>;
. . .
case <const_expression_n>: <statement_n>;
[ default: <statement_n+1>; ]
} ;
04/19/23 Assoc. Prof. Stoyan Bonev 29
Multiple Selectors - Examples
• Syntax diagram illustrates selector stmt.
04/19/23 Assoc. Prof. Stoyan Bonev 30
Multiple Selectors - Examples
• C, C++, Java switch statement Comments:– Expressions are integer type– The default segment is for unrepresented values of the
control expression– The switch construct does not provide implicit branches at
the end of its code segments. This allows control flow through more than one selectable code segment on a single execution
– To logically separate these segments, an explicit branch must be included
– The break statement, which is actually a restricted goto, is normally used for exiting switch constructs
04/19/23 Assoc. Prof. Stoyan Bonev 31
Multiple Selectors - Examples
• C# switch statement• It differs from its C-like predecessors in that a
static semantic rule disallows the implicit execution of more than one case segment. The rule is that every selectable segment must end with explicit unconditional branch statement: either a break, which transfers control out of the switch, or a goto, which can transfer control to one of the selectable case segments.
• Example on next slide
04/19/23 Assoc. Prof. Stoyan Bonev 32
Multiple Selectors - Examples
• C# switch statement switch (value) { case -1: negatives++;
break; case 0: Zeros++;
goto case 1;case 1: Positives++;
break; default: Console.WriteLine(“Error in switch”);}
04/19/23 Assoc. Prof. Stoyan Bonev 33
Multiple Selection using if
• In many situations, a switch construct is inadequate for multiple selection. For example, when selections must be made on the basis of a Boolean expression rather than some ordinal type, nested two-way selectors can be used to simulate multiple selection.
• In order to alleviate the poor readability of deeply nested two-way selectors, Ada, Perl have been extended specifically. The else-if sequences are replaced with a special keyword (elsif) and the special closing word on the nested if is dropped
• Example on next slide
04/19/23 Assoc. Prof. Stoyan Bonev 34
Multiple Selection using if
if Count < 10 then Bag1 := True; if Count < 10 then
elsif Count < 100 then Bag2 := True; Bag1 := True;
elsif Count < 1000 then Bag3 := True; else
end if; if Count < 100 then
Bag2 := True;
else
if Count < 1000 then
Bag3 := True;
end if;
end if;
end if;
04/19/23 Assoc. Prof. Stoyan Bonev 35
Multiple Selection using if
if Count < 10 then Bag1 := True; elsif Count < 100 then Bag2 := True; elsif Count < 1000 then Bag3 := True; end if;
if Count < 10 then Bag1 := True; end if if Count < 100 then Bag2 := True; end if if Count < 1000 then Bag3 := True; end if;
Iterative statements
04/19/23 Assoc. Prof. Stoyan Bonev 37
Iterative Statements
• An iterative statement causes a statement or a collection of statements to be executed 0, 1, or more times. An iterative construct is called loop
• Basic Design Issues (questions):– How is the iteration controlled
• Counter controlled loops • Logically controlled loops• Structure iterators
– Where should control mechanism appear in the loop • Pretest condition• Posttest condition
04/19/23 Assoc. Prof. Stoyan Bonev 38
Iterative Statements
• The loop body is the collection of statements whose execution is controlled by the iteration statement.
• The iteration statement and the associated loop body together form an iteration construct.
• What does the term pretest mean?• What does the term posttest mean?
04/19/23 Assoc. Prof. Stoyan Bonev 39
Counter-Controlled Loops• All loops have a loop variable, in which the count
value is maintained. Three Loop parameters are:– Initial and terminal value of the loop variable– Difference btw sequential loop variable values, stepsize
• Specific Design Issues:– Type and scope of the loop variable– Value of the loop variable at loop termination– Is it legal to change loop variable or loop parameters in
the loop body?– Should loop parameters be evaluated only once, or once
for every iteration
04/19/23 Assoc. Prof. Stoyan Bonev 40
The Do stmt of Fortran 95
• Formal syntax: Do label variable = initial, terminal [,stepsize]
• Examples: Do 100 I = 1,20,1
. . .
100 Continue
04/19/23 Assoc. Prof. Stoyan Bonev 41
For … Next Loop Statement of VBasic:
For counter = initVal To endVal [Step incVal] . . . One or more VB statements . . .Next [counter]
04/19/23 Assoc. Prof. Stoyan Bonev 42
The for stmt of C-like PL
• Formal syntax: for(<exp1> ; <exp2> ; <exp3>) <statemnetnt> ;
• Flow chart and syntax diagram
• Examples: for (int j=1; j<=10 ; j++) b[j] = j+j;
for (sum=0, k=1 ; k<=10 ; sum+=k, k++) NULL;
for ( ; ; ) cout <<“\nAUBG”;
04/19/23 Assoc. Prof. Stoyan Bonev 43
Logically Controlled Loops
• Collections of statements are repeatedly executed, but repetition control is based on Boolean expression rather than a counter.
• Logically controlled loops are more general than counter-controlled loops.
• Every counting loop can be built with a logical loop, but the reverse is not true.
04/19/23 Assoc. Prof. Stoyan Bonev 44
For loop converted to while
for(<exp1> ; <exp2> ; <exp3>) <statement>;
<exp1> ;
while (<exp2>)
{
<statement>;
<exp3>;
}
04/19/23 Assoc. Prof. Stoyan Bonev 45
Logically Controlled Loops
• Design Issues:– Should the control be pretest or posttest?– Should the logically controlled loop be a
special modified form of a counting statement or it should be a totally separate statement
04/19/23 Assoc. Prof. Stoyan Bonev 46
Logic Loops - Syntax
• Pretest loop while ( <control_expression> )
<loop body>
• Flow chart and syntax diagram• Posttest loop
do<loop body>
while ( <control expression> )
• Flow chart
04/19/23 Assoc. Prof. Stoyan Bonev 47
Logic Loops – C# Examples
sum = 0; indat = Int32.Parse(Console.ReadLine()); while (indat >= 0) {
sum += indat;indat = Int32.Parse(Console.ReadLine());
}
value = Int32.Parse(Console.ReadLine()); do {
value /= 10;digits++;
} while (value > 0);
04/19/23 Assoc. Prof. Stoyan Bonev 48
Do Loops in VBasic
Do While boolean expressionstatements
Loop------------------------------------------Do Until boolean expression
statementsLoop------------------------------------------Do
statementsLoop While boolean expression------------------------------------------Do
statementsLoop Until boolean expression------------------------------------------Do
statementsLoop
04/19/23 Assoc. Prof. Stoyan Bonev 49
Do Loops in VBasic
Pretest loops
----------------------------------------- Do While boolean expressionstatements
Loop-----------------------------------------Do Until boolean expressionstatements
Loop-----------------------------------------
04/19/23 Assoc. Prof. Stoyan Bonev 50
Do Loops in VBasic
Posttest loops
-----------------------------------------Do statements
Loop While boolean expression-----------------------------------------Do statements
Loop Until boolean expression-----------------------------------------
04/19/23 Assoc. Prof. Stoyan Bonev 51
Do Loops in VBasic
Infinite /endless/ loops
-----------------------------------------Do statements
Loop -----------------------------------------
04/19/23 Assoc. Prof. Stoyan Bonev 52
User-Located Loop Controls
• Basic idea: to create an option for the programmer to choose a location for loop control other than the top or bottom of the loop.
• It is easy to implement user-located loop control, or exit of the loop.
• It is more complicated to consider whether a single loop or several nested loops can be exited.
• More comments on next slide.
04/19/23 Assoc. Prof. Stoyan Bonev 53
User-Located Loop Controls
• Mechanism to unconditionally exit loop– C/C++: unconditional unlabeled exit – break– Java/Perl/C#: unconditional labeled exit – ( break in
Java, C# and last in Perl)
• Mechanism to interrupt current iteration and stay within loop– C/C++: unlabeled continue– Java/Perl/C#: statements similar to continue, except
that they can include labels to indicate which loop is to be continued
04/19/23 Assoc. Prof. Stoyan Bonev 54
Loops – Practical Application
• Iterative processing concept (intro for beginners) if (there are any steps to repeat)
{
loop required;
}
else
{
no loop required
}
04/19/23 Assoc. Prof. Stoyan Bonev 55
Loops – Practical Application
if (know in advance how many times to repeat) { use Counter controlled loop; } else { use Sentinel controlled loop; or
use Flag controlled loop; oruse End File controlled loop; oruse Input Validation loop; oruse General conditional loop;
}
04/19/23 Assoc. Prof. Stoyan Bonev 56
Loop Patterns
• Sentinel Controlled Loops1. Read the first data item.2. while the sentinel value has not been read 3. Process the data item. 4. Read the next data item.
• Flag Controlled Loops1. Set the flag to false.2. while the flag is false
3. Perform some action. 4. Reset the flag to true if the anticipated event occurred.
04/19/23 Assoc. Prof. Stoyan Bonev 57
Example of Sentinel Controlled Loop
#define SENTINEL (-99). . .int sum=0, var;cout << "\nEnter value:"; cin >> var; while (var != SENTINEL)
{ sum += var; cin >> var; }
cout << sum;
04/19/23 Assoc. Prof. Stoyan Bonev 58
Example of End File (End of Data) Controlled Loop
int var, sum=0;cout << "\nEnter value:"; cin >> var;while ( !(cin.eof()) ) {
sum+=var; cout << Enter new value:"; cin >> var; }cout << "\n\nSum=" << sum ;
04/19/23 Assoc. Prof. Stoyan Bonev 59
Example of Input Validation Loop
int numobs;. . .cout << “\nEnter number of observed values:”;cin >> numobs;while (numobs <=0 ){ cout <<“\nNegative or Zero observations invalid.”; cout << “ Try again:”; cin >> numobs;}
04/19/23 Assoc. Prof. Stoyan Bonev 60
Iteration Based on Data Structures
• Instead of using a counter or a Boolean expression to control the iterations processed, these loops use the number of elements in a user defined dynamic data structure.
• This topic is a special subject of the lecture titled Iteration Based on Data Structures.
04/19/23 Assoc. Prof. Stoyan Bonev 61
Unconditional Branching
• An unconditional branch stmt transfers execution control to a specific place in the program.
• Heat debate in PL design: should goto be a part of any HLL, and if so whether its use should be restricted.
• Goto is the most powerful and flexible stmt.• Goto is the most dangerous stmt.• Without restrictions on use, imposed by language
design or by programming standards, goto makes programs very difficult to read and maintain.
04/19/23 Assoc. Prof. Stoyan Bonev 62
Unconditional Branching
• A few languages have been designed without goto – Modula-2, Java
• Kernighan&Ritchie call goto infinitely abusable but their C PL includes goto.
• C# (a relatively new PL) provides a legitimate use of goto in the switch statement.
• All of the loop exit statements (break, continue) are actually camouflaged gotos.
04/19/23 Assoc. Prof. Stoyan Bonev 63
Exercise 4a
Components of Programming Languages. Part III.
Practical
• StatementLevel Control Structures
Assignments under discussion are based on lecture 4.
04/19/23 Assoc. Prof. Stoyan Bonev 64
Task 1Using counter controlled loop statement, logically pretest
controlled loop statement and logically posttest controlled loop statements, write in three versions a program that:
• displays the squares of numbers from 0 to 19 (step size +1) all at the same line;
• displays squares (x*x) and cubes (x*x*x) of numbers from 0 to 10 using a three column format:
x sqr(x) cube(x)• displays FahrenheitCelsius table in a range and format
chosen by the student. The relation Celsius/Fahrenheit is Celsius = 5 / 9 * (Fahrenheit – 32)
04/19/23 Assoc. Prof. Stoyan Bonev 65
Reminder
Quiz #1
on
Components of PL
ISBN 0-321-49362-1
Chapter 8
Statement-Level Control Structures
Copyright © 2009 Addison-Wesley. All rights reserved. 1-67Copyright © 2009 Addison-Wesley. All rights reserved. 1-67
Chapter 8 Topics
• Introduction• Selection Statements• Iterative Statements• Unconditional Branching• Guarded Commands• Conclusions
Copyright © 2009 Addison-Wesley. All rights reserved. 1-68Copyright © 2009 Addison-Wesley. All rights reserved. 1-68
Levels of Control Flow
– Within expressions (Chapter 7)– Among program units (Chapter 9)– Among program statements (this
chapter)
Copyright © 2009 Addison-Wesley. All rights reserved. 1-69Copyright © 2009 Addison-Wesley. All rights reserved. 1-69
Control Statements: Evolution
• FORTRAN I control statements 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
Copyright © 2009 Addison-Wesley. All rights reserved. 1-70Copyright © 2009 Addison-Wesley. All rights reserved. 1-70
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?
Copyright © 2009 Addison-Wesley. All rights reserved. 1-71Copyright © 2009 Addison-Wesley. All rights reserved. 1-71
Selection Statements
• A selection statement provides the means of choosing between two or more paths of execution
• Two general categories:– Two-way selectors– Multiple-way selectors
Copyright © 2009 Addison-Wesley. All rights reserved. 1-72Copyright © 2009 Addison-Wesley. All rights reserved. 1-72
Two-Way Selection Statements
• General form:if control_expression
then clauseelse clause
• Design Issues:– What is the form and type of the control
expression?– How are the then and else clauses specified?– How should the meaning of nested selectors
be specified?
Copyright © 2009 Addison-Wesley. All rights reserved. 1-73Copyright © 2009 Addison-Wesley. All rights reserved. 1-73
The Control Expression
• If the then reserved word or some other syntactic marker is not used to introduce the then clause, the control expression is placed in parentheses
• In C89, C99, Python, and C++, the control expression can be arithmetic
• In languages such as Ada, Java, Ruby, and C#, the control expression must be Boolean
Copyright © 2009 Addison-Wesley. All rights reserved. 1-74Copyright © 2009 Addison-Wesley. All rights reserved. 1-74
Clause Form
• In many contemporary languages, the then and else clauses can be single statements or compound statements
• In Perl, all clauses must be delimited by braces (they must be compound)
• In Fortran 95, Ada, and Ruby, clauses are statement sequences
• Python uses indentation to define clauses if x > y : x = y
print "case 1"
Copyright © 2009 Addison-Wesley. All rights reserved. 1-75Copyright © 2009 Addison-Wesley. All rights reserved. 1-75
Nesting Selectors
• Java example if (sum == 0)
if (count == 0)
result = 0;
else result = 1;
• Which if gets the else? • Java's static semantics rule: else matches
with the nearest if
Copyright © 2009 Addison-Wesley. All rights reserved. 1-76Copyright © 2009 Addison-Wesley. All rights reserved. 1-76
Nesting Selectors (continued)
• To force an alternative semantics, compound statements may be used:
if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;• The above solution is used in C, C++, and C#• Perl requires that all then and else clauses to be
compound
Copyright © 2009 Addison-Wesley. All rights reserved. 1-77Copyright © 2009 Addison-Wesley. All rights reserved. 1-77
Nesting Selectors (continued)
• Statement sequences as clauses: Ruby if sum == 0 then if count == 0 then
result = 0
else
result = 1
end
end
Copyright © 2009 Addison-Wesley. All rights reserved. 1-78Copyright © 2009 Addison-Wesley. All rights reserved. 1-78
Nesting Selectors (continued)
• Python if sum == 0 : if count == 0 :
result = 0
else :
result = 1
Copyright © 2009 Addison-Wesley. All rights reserved. 1-79Copyright © 2009 Addison-Wesley. All rights reserved. 1-79
Multiple-Way Selection Statements• Allow the selection of one of any number of
statements or statement groups• Design Issues:
1. What is the form and type of the control expression?2. How are the selectable segments specified?3. Is execution flow through the structure restricted to
include just a single selectable segment?4. How are case values specified?5. What is done about unrepresented expression values?
Copyright © 2009 Addison-Wesley. All rights reserved. 1-80Copyright © 2009 Addison-Wesley. All rights reserved. 1-80
Multiple-Way Selection: Examples
• C, C++, and Javaswitch (expression) {
case const_expr_1: stmt_1;
…case const_expr_n: stmt_n;
[default: stmt_n+1]
}
Copyright © 2009 Addison-Wesley. All rights reserved. 1-81Copyright © 2009 Addison-Wesley. All rights reserved. 1-81
Multiple-Way Selection: Examples
• Design choices for C’s switch statement1. Control expression can be only an integer type2. Selectable segments can be statement
sequences, blocks, or compound statements3. 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)
Copyright © 2009 Addison-Wesley. All rights reserved. 1-82Copyright © 2009 Addison-Wesley. All rights reserved. 1-82
Multiple-Way Selection: Examples
• C#– Differs from C in that it has a static semantics
rule that disallows the implicit execution of more than one segment
– Each selectable segment must end with an unconditional branch (goto or break)
– Also, in C# the control expression and the case constants can be strings
Copyright © 2009 Addison-Wesley. All rights reserved. 1-83Copyright © 2009 Addison-Wesley. All rights reserved. 1-83
Multiple-Way Selection: Examples
• Ada 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
Copyright © 2009 Addison-Wesley. All rights reserved. 1-84Copyright © 2009 Addison-Wesley. All rights reserved. 1-84
Multiple-Way Selection: Examples
• Ada design choices: 1. Expression can be any ordinal type 2. Segments can be single or compound 3. Only one segment can be executed per
execution of the construct 4. Unrepresented values are not allowed• Constant List Forms: 1. A list of constants 2. Can include: - Subranges - Boolean OR operators (|)
Copyright © 2009 Addison-Wesley. All rights reserved. 1-85Copyright © 2009 Addison-Wesley. All rights reserved. 1-85
Multiple-Way Selection: Examples
• Ruby has two forms of case statements 1. One form uses when conditions leap = case when year % 400 == 0 then true
when year % 100 == 0 then false
else year % 4 == 0
end
2. The other uses a case value and when values case in_val when -1 then neg_count++ when 0 then zero_count++ when 1 then pos_count++ else puts "Error – in_val is out of range" end
Copyright © 2009 Addison-Wesley. All rights reserved. 1-86Copyright © 2009 Addison-Wesley. All rights reserved. 1-86
Multiple-Way Selection Using if
• Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses, for example in Python:
if count < 10 :
bag1 = True
elif count < 100 :
bag2 = True
elif count < 1000 :
bag3 = True
Copyright © 2009 Addison-Wesley. All rights reserved. 1-87Copyright © 2009 Addison-Wesley. All rights reserved. 1-87
Multiple-Way Selection Using if
• The Python example can be written as a Ruby case
case when count < 10 then bag1 = true
when count < 100 then bag2 = true
when count < 1000 then bag3 = true
end
Copyright © 2009 Addison-Wesley. All rights reserved. 1-88Copyright © 2009 Addison-Wesley. All rights reserved. 1-88
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?
Copyright © 2009 Addison-Wesley. All rights reserved. 1-89Copyright © 2009 Addison-Wesley. All rights reserved. 1-89
Counter-Controlled Loops
• A counting iterative statement has a loop variable, and a means of specifying the initial and terminal, and stepsize values
• Design Issues:1. What are the type and scope of the loop
variable?2. 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?
3. Should the loop parameters be evaluated only once, or once for every iteration?
Copyright © 2009 Addison-Wesley. All rights reserved. 1-90Copyright © 2009 Addison-Wesley. All rights reserved. 1-90
Iterative Statements: Examples
• FORTRAN 95 syntaxDO label var = start, finish [, stepsize]
• Stepsize can be any value but zero• Parameters can be expressions• Design choices:
1. Loop variable must be INTEGER2. 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
3. Loop parameters are evaluated only once
Copyright © 2009 Addison-Wesley. All rights reserved. 1-91Copyright © 2009 Addison-Wesley. All rights reserved. 1-91
Iterative Statements: Examples
• FORTRAN 95 : a second form: [name:] Do variable = initial, terminal [,stepsize]
…
End Do [name]
- Cannot branch into either of Fortran’s Do statements
Copyright © 2009 Addison-Wesley. All rights reserved. 1-92Copyright © 2009 Addison-Wesley. All rights reserved. 1-92
Iterative Statements: Examples
• Adafor var in [reverse] discrete_range loop ...end loop
• Design choices: - Type of the loop variable is that of the discrete
range (A discrete range is a sub-range of an integer or enumeration type).
- Loop variable does not exist outside the loop - The loop variable cannot be changed in the
loop, but the discrete range can; it does not affect loop control
- The discrete range is evaluated just once• Cannot branch into the loop body
Copyright © 2009 Addison-Wesley. All rights reserved. 1-93Copyright © 2009 Addison-Wesley. All rights reserved. 1-93
Iterative Statements: Examples
• C-based languagesfor ([expr_1] ; [expr_2] ; [expr_3]) statement
- The expressions can be whole 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– If the second expression is absent, it is an infinite loop
• Design choices: - There is no explicit loop variable - Everything can be changed in the loop - The first expression is evaluated once, but the other two
are evaluated with each iteration
Copyright © 2009 Addison-Wesley. All rights reserved. 1-94Copyright © 2009 Addison-Wesley. All rights reserved. 1-94
Iterative Statements: Examples
• C++ differs from C in two ways:1. The control expression can also be Boolean2. The initial expression can include variable
definitions (scope is from the definition to the end of the loop body)
• Java and C#– Differs from C++ in that the control
expression must be Boolean
Copyright © 2009 Addison-Wesley. All rights reserved. 1-95Copyright © 2009 Addison-Wesley. All rights reserved. 1-95
Iterative Statements: Examples
• Python for loop_variable in object: - loop body [else: - else clause]
– The object is often a range, which is either a list of values in brackets ([2, 4, 6]), or a call to the range function (range(5), which returns 0, 1, 2, 3, 4
– The loop variable takes on the values specified in the given range, one for each iteration
– The else clause, which is optional, is executed if the loop terminates normally
Copyright © 2009 Addison-Wesley. All rights reserved. 1-96Copyright © 2009 Addison-Wesley. All rights reserved. 1-96
Iterative Statements: Logically-Controlled Loops
• Repetition control is based on a Boolean expression
• Design issues:– Pretest or posttest?– Should the logically controlled loop be a
special case of the counting loop statement or a separate statement?
Copyright © 2009 Addison-Wesley. All rights reserved. 1-97Copyright © 2009 Addison-Wesley. All rights reserved. 1-97
Iterative Statements: Logically-Controlled Loops: Examples
• C and C++ have both pretest and posttest forms, in which the control expression can be arithmetic:while (ctrl_expr) do
loop body loop body
while (ctrl_expr)
• Java is like C and C++, except the control expression must be Boolean (and the body can only be entered at the beginning -- Java has no goto
Copyright © 2009 Addison-Wesley. All rights reserved. 1-98Copyright © 2009 Addison-Wesley. All rights reserved. 1-98
Iterative Statements: Logically-Controlled Loops: Examples
• Ada has a pretest version, but no posttest
• FORTRAN 95 has neither
• Perl and Ruby have two pretest logical loops, while and until. Perl also has two posttest loops
Copyright © 2009 Addison-Wesley. All rights reserved. 1-99Copyright © 2009 Addison-Wesley. All rights reserved. 1-99
Iterative Statements: 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)
• Simple design for single loops (e.g., break)• Design issues for nested loops
1. Should the conditional be part of the exit?2. Should control be transferable out of more
than one loop?
Copyright © 2009 Addison-Wesley. All rights reserved. 1-100Copyright © 2009 Addison-Wesley. All rights reserved. 1-100
Iterative Statements: User-Located Loop Control Mechanisms break and continue• C , C++, Python, Ruby, and C# have
unconditional unlabeled exits (break)• Java and Perl have unconditional labeled
exits (break in Java, last in Perl)• C, C++, and Python have an unlabeled
control statement, continue, that skips the remainder of the current iteration, but does not exit the loop
• Java and Perl have labeled versions of continue
Copyright © 2009 Addison-Wesley. All rights reserved. 1-101Copyright © 2009 Addison-Wesley. All rights reserved. 1-101
Iterative Statements: 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 for can be used to build a user-defined iterator:for (p=root; p==NULL; traverse(p)){
}
Copyright © 2009 Addison-Wesley. All rights reserved. 1-102Copyright © 2009 Addison-Wesley. All rights reserved. 1-102
Iterative Statements: Iteration Based on Data Structures (continued)
PHP - current points at one element of the array - next moves current to the next element - reset moves current to the first element
• Java - For any collection that implements the Iterator interface - next moves the pointer into the collection - hasNext is a predicate - remove deletes an element
• Perl has a built-in iterator for arrays and hashes, foreach
Copyright © 2009 Addison-Wesley. All rights reserved. 1-103Copyright © 2009 Addison-Wesley. All rights reserved. 1-103
Iterative Statements: Iteration Based on Data Structures (continued)
• Java 5.0 (uses for, although it is called foreach) - For arrays and any other class that implements Iterable interface, e.g., ArrayList
for (String myElement : myList) { … }
• 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
Copyright © 2009 Addison-Wesley. All rights reserved. 1-104
Iterative Statements: Iteration Based on Data Structures (continued)• Lua
– Lua has two forms of its iterative statement, one like Fortran’s Do, and a more general form:
for variable_1 [, variable_2] in iterator(table) do
…
end
– The most commonly used iterators are pairs and ipairs
Copyright © 2009 Addison-Wesley. All rights reserved. 1-104
Copyright © 2009 Addison-Wesley. All rights reserved. 1-105Copyright © 2009 Addison-Wesley. All rights reserved. 1-105
Unconditional Branching
• Transfers execution control to a specified place in the program
• 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., Java)• C# offers goto statement (can be used in switch
statements)• Loop exit statements are restricted and somewhat
camouflaged goto’s
Copyright © 2009 Addison-Wesley. All rights reserved. 1-106Copyright © 2009 Addison-Wesley. All rights reserved. 1-106
Guarded Commands
• Designed by Dijkstra• Purpose: to support a new programming
methodology that supported verification (correctness) during development
• Basis for two linguistic mechanisms for concurrent programming (in CSP and Ada)
• Basic Idea: if the order of evaluation is not important, the program should not specify one
Copyright © 2009 Addison-Wesley. All rights reserved. 1-107Copyright © 2009 Addison-Wesley. All rights reserved. 1-107
Selection Guarded Command
• Formif <Boolean exp> -> <statement>[] <Boolean exp> -> <statement> ...[] <Boolean exp> -> <statement>fi
• Semantics: when construct is reached, – Evaluate all Boolean expressions– If more than one are true, choose one non-
deterministically– If none are true, it is a runtime error
Copyright © 2009 Addison-Wesley. All rights reserved. 1-108Copyright © 2009 Addison-Wesley. All rights reserved. 1-108
Loop Guarded Command
• Formdo <Boolean> -> <statement>[] <Boolean> -> <statement> ...[] <Boolean> -> <statement>od
• Semantics: for each iteration– Evaluate all Boolean expressions– If more than one are true, choose one non-
deterministically; then start loop again– If none are true, exit loop
Copyright © 2009 Addison-Wesley. All rights reserved. 1-109Copyright © 2009 Addison-Wesley. All rights reserved. 1-109
Guarded Commands: Rationale
• Connection between control statements and program verification is intimate
• Verification is impossible with goto statements
• Verification is possible with only selection and logical pretest loops
• Verification is relatively simple with only guarded commands
Copyright © 2009 Addison-Wesley. All rights reserved. 1-110Copyright © 2009 Addison-Wesley. All rights reserved. 1-110
Conclusion
• Variety of statement-level structures• Choice of control statements beyond
selection and logical pretest loops is a trade-off between language size and writability
• Functional and logic programming languages are quite different control structures
Thank Youfor
Your attention