ControlStructures LoopsConditionalsAndCaseStatements PDF
ControlStructures LoopsConditionalsAndCaseStatements PDF
1
Agenda
1 Session Overview
3 Conclusion
2
What is the course about?
Textbook:
» Programming Language Pragmatics (3rd Edition)
Michael L. Scott
Morgan Kaufmann
ISBN-10: 0-12374-514-4, ISBN-13: 978-0-12374-514-4, (04/06/09)
Additional References:
» Osinski, Lecture notes, Summer 2008
» Barrett, Lecture notes, Fall 2008
» Gottlieb, Lecture notes, Fall 2009
» Grimm, Lecture notes, Spring 2010
3
Session Agenda
Session Overview
Control Structures: Loops, Conditionals, and Case Statements
Conclusion
4
Icons / Metaphors
Information
Common Realization
Knowledge/Competency Pattern
Governance
Alignment
Solution Approach
55
Session 2 Review
Use of Types
Name, Scope, and Binding
Names
Binding
Early vs. Late Binding Time Advantages Detailed
Lifetimes
Lifetime and Storage Management
Garbage Collection
Scopes
Scope Rules
Scope Rules – Example: Static vs. Dynamic
The Meaning of Names within a Scope
Bindings of Referencing Environments
Separate Compilation
Conclusions
6
Agenda
1 Session Overview
3 Conclusion
7
Control Structures: Loops, Conditionals, and Case Statements
Control Flow
Control Structures
Statement Grouping
Expression Evaluation
Sequencing
Semicolons
Selection
Lists / Iteration
Recursion
Conclusions
8
Control Flow (1/3)
9
Control Flow (2/3)
10
Control Flow (3/3)
11
Control Structures (1/2)
12
Control Structures (2/2)
13
Statement Grouping
14
Expression Evaluation (1/15)
16
Expression Evaluation (3/15)
Figure 6.1 Operator precedence levels in Fortran, Pascal, C, and Ada. The operator s at the top of the figure group most tightly.
17
Expression Evaluation (4/15)
» inviolability of parentheses
18
Expression Evaluation (5/15)
Short-circuiting
»Consider (a < b) && (b < c):
• If a >= b there is no point evaluating
whether b < c because (a < b) && (b
< c) is automatically false
»Other similar situations
if (b != 0 && a/b == c) ...
if (*p && p->foo) ...
if (f || messy()) ...
19
Expression Evaluation (6/15)
21
Expression Evaluation (8/15)
Orthogonality
» Features that can be used in any
combination
• Meaning is consistent
if (if b != 0 then a/b == c else false) then ...
if (if f then true else messy()) then ...
Aggregates
» Compile-time constant values of user-defined
composite types
22
Expression Evaluation (9/15)
Initialization
» Pascal has no initialization facility (assign)
» Assignment statements provide a way to set a value of a
variable.
» Language may not provide a way to specify an initial value.
This can lead to bugs.
» Some languages provide default initialization.
• C initializes external variables to zero
» System may check dynamically if a variable is uninitialized
• IEEE floating point uses special bit pattern (NaN)
• Requires hardware support and expensive software checking
» Compiler may statically check – Java, C#
• May be overly conservative
» OO-languages use constructors to initialize dynamically
allocated variables
23
Expression Evaluation (10/15)
Assignment
» statement (or expression) executed for its side effect
» assignment operators (+=, -=, etc)
• handy
• avoid redundant work (or need for optimization)
• perform side effects exactly once
» C --, ++
• postfix form
24
Expression Evaluation (11/15)
Side Effects
» often discussed in the context of functions
» a side effect is some permanent state change
caused by execution of function
• some noticable effect of call other than return
value
• in a more general sense, assignment statements
provide the ultimate example of side effects
– they change the value of a variable
– Side effects change the behavior of subsequent
statements and expressions.
25
Expression Evaluation (12/15)
26
Expression Evaluation (13/15)
27
Expression Evaluation (14/15)
29
Sequencing
Sequencing
»specifies a linear ordering on
statements
• one statement follows another
»very imperative, Von-Neuman
30
Sequencing
31
Semicolons
begin X := 1; { X = 1;
Y := 2 Y = 2;
end }
32
Selection (1/13)
Selection
»sequential if statements
if ... then ... else
if ... then ... elsif ... else
(cond
(C1) (E1)
(C2) (E2)
...
(Cn) (En)
(T) (Et)
)
33
Selection (2/13)
34
Selection (3/13)
if Condition1 then
if Condition2 then
Statements1
else
Statements2
The solution is to use end markers. In Ada:
if Condition1 then
if Condition2 then
Statements1
end if;
else
Statements2
end if;
35
Selection (4/13)
Selection
» Fortran computed gotos
» jump code
• for selection and logically-controlled loops
• no point in computing a Boolean value into a
register, then testing it
• instead of passing register containing Boolean out of
expression as a synthesized attribute, pass inherited
attributes INTO expression indicating where to jump
to if true, and where to jump to if false
36
Selection (5/13)
37
Selection (6/13)
38
Selection (7/13)
39
Selection (8/13)
Short-Circuit Evaluation
if (x/y > 5) { z = ... } // what if y == 0?
if (y == 0 || x/y > 5) { z = ... }
But binary operators normally evaluate both
arguments. Solutions:
» a lazy evaluation rule for logical operators (LISP, C)
C1 && C2 // don’t evaluate C2 if C1 is false
C1 || C2 // don’t evaluate C2 if C1 is true
» a control structure with a different syntax (ADA)
-- don’t evaluate C2
if C1 and then C2 then -- if C1 is false
if C1 or else C2 then -- if C1 is true
40
Selection (9/13)
Multi-way Selection
» Case statement needed when there are many
possibilities “at the same logical level” (i.e. depending
on the same condition)
case Next_Char is
when ’I’ => Val := 1;
when ’V’ => Val := 5;
when ’X’ => Val := 10;
when ’C’ => Val := 100;
when ’D’ => Val := 500;
when ’M’ => Val := 1000;
when others => raise Illegal_Roman_Numeral;
end case;
Can be simulated by sequence of if-statements,
but logic is obscured
41
Selection (10/13)
42
Selection (11/13)
Implementation of Case:
» A possible implementation for C/C++/JAVA/ADA style
case (if we have a finite set of possibilities, and the
choices are computable at compile-time):
• build table of addresses, one for each choice
• compute value
• transform into table index
• get table element at index and branch to that address
• execute
• branch to end of case statement
» This is not the typical implementation for a
ML/HASKELL style case
43
Selection (12/13)
Complications
case (x+1) is
when integer’first..0 ) Put_Line ("negative");
when 1 ) Put_Line ("unit");
when 3 | 5 | 7 | 11 ) Put_Line ("small prime");
when 2 | 4 | 6 | 8 | 10 ) Put_Line ("small even");
when 21 ) Put_Line ("house wins");
when 12..20 | 22..99 ) Put_Line ("manageable");
when others ) Put_Line ("irrelevant");
end case;
Implementation would be a combination of tables and if
statements
44
Selection (13/13)
Enumeration-controlled
»Pascal or Fortran-style for loops
• scope of control variable
• changes to bounds within loop
• changes to loop variable within loop
• value after the loop
46
Iteration / Loops (2/14)
Indefinite Loops
» All loops can be expressed as while-loops
• good for invariant/assertion reasoning
» condition evaluated at each iteration
» if condition initially false, loop is never executed
while condition loop ... end loop;
is equivalent to
if condition then
while condition loop ... end loop
end if;
if condition has no side-effects
47
Iteration / Loops (3/14)
first := True;
while (first or else condition) loop
...
first := False;
end loop;
48
Iteration / Loops (4/14)
Breaking Out
» A more common need is to be able to break out of
the loop in the middle of an iteration.
• break (C/C++, JAVA)
• last (PERL)
• exit (ADA)
loop
... part A ...
exit when condition;
... part B ...
end loop;
49
Iteration / Loops (5/14)
50
Iteration / Loops (6/14)
Definite Loops
» Counting loops are iterators over discrete domains:
» Design issues:
51
Iteration / Loops (7/14)
Evaluation of Bounds
» Yes – in ADA, bounds are evaluated once before iteration starts. Note:
the above loop uses abominable style. C/C++/JAVA loop has hybrid
semantics:
52
Iteration / Loops (8/14)
53
Iteration / Loops (9/14)
Different Increments
ALGOL 60:
C/C++:
ADA:
54
Iteration / Loops (10/14)
Non-Numeric Domains
ADA form generalizes to discrete types:
iterator = Collection.Iterate();
element thing = iterator.first;
for (element thing = iterator.first;
iterator.more_elements();
thing = iterator.next()) {
...
}
55
Iteration / Loops (11/14)
List Comprehensions
» Shorthand for:
c2 = [ ]
for x in l:
if x < 3:
for y in t:
c2.append((x,y))
56
Iteration / Loops (12/14)
57
Iteration / Loops (13/14)
Efficient Exponentiation
58
Iteration / Loops (14/14)
59
Recursion (1/3)
Recursion
»equally powerful to iteration
»mechanical transformations back and
forth
»often more intuitive (sometimes less)
»naïve implementation less efficient
• no special syntax required
• fundamental to functional languages like
Scheme
60
Recursion (2/3)
Tail recursion
» No computation follows recursive call
• In this case we do not need to keep multiple copies of the local
variables since, when one invocation calls the next, the first is
finished with its copy of the variables and the second one can
reuse them rather than pushing another set of local variables on
the stack. This is very helpful for performance.
int gcd (int a, int b) {
/* assume a, b > 0 */
if (a == b) return a;
else if (a > b) return gcd (a - b,b);
else return gcd (a, b – a);
}
61
Recursion (3/3)
1 APL
2 Ada95
3 J
4 Perl
5 Python
63
History
64
Typing and Scope
Dynamic Scope
Two Types – Numbers and Characters
» Automatic conversion between floating point and
integer
» Strings are character vectors
» Boolean values are 0 and 1
Type associated with Values, not names
» Tagged types
» Run-time checking
65
Example
66
Example (continued)
This line of code calculates the prime numbers from 2 to the starting
value of R, in this example 20.
the "iota funtion" of R filles a vector (and that will be R again) with
numbers from 1 to the value of the variable (20 in this example), the
first element is dropped (that is the 1); so to the right of the "/" there
will be 2 3 4 5 ... 18 19 20
the "small.circle-dot-multiply" defines an outer product so all
elements of R are multiplied by all elements of R giving a matrix;
check whether elements of R are in the matrix and make a vector
containing "1"-s at the place where that is true and "0"-s where that
is not true
inverse that vector and use it to grab that elements from R using the
"over" function
67
Syntax
Simple syntax
» Right to left evaluation
» infix operators and functions
» modifiers (verbs and adverbs)
• Modifiers are operators that modify the operation of other operators
» Can be parsed with only 3 states (Zaks)
Expression Language
» No selection or looping statements
» Only goto
Scalar operators automatically extend to
matrices
» Loops are unusual in APL
68
Operations on numbers
Monadic
⌈B, ⌊B -- ceiling/floor
⌈3.4 = 4
Dyadic
A⌈B, A⌊B -- max, min
A⌈B returns maximum of x or y 2⌈3=3
{ln} {log} (circled start symbol)
{ln}B returns the natural log of B. A{log}B returns the base-A log of B.
69
Operations on Arrays
-- interval
n returns a vector of integers from origin to n
4 = 1 2 3 4
-- size 0 1 2 3 = 4
Dyadic
-- shape
reshapes an array
2 20 1 2 3 creates a 2 x 2 array
-- Transpose
Rotates an array along the major diagonal
-- Domino
Does matrix inversion and division
70
Operations on Arrays (continued)
71
Operators on Operators
72
Appendix
1 APL
2 Ada95
3 J
4 Perl
5 Python
73
Ada95
Overview of Ada95
» http://cs.nyu.edu/courses/fall01/G22.2110-
001/pl.lec3.ppt
Ada Summary
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/AdaIntro.html
Notes on Ada
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/AdaNotes.html
Syntax of Ada95:
» http://www.cs.nyu.edu/courses/fall05/G22.2110-
001/RM-P.html
74
Appendix
1 APL
2 Ada95
3 J
4 Perl
5 Python
75
J
See
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/JDictionary.pdf
76
Appendix
1 APL
2 Ada95
3 J
4 Perl
5 Python
77
Perl
See
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/PrototypingInPerl.pdf
78
Appendix
1 APL
2 Ada95
3 J
4 Perl
5 Python
79
Python
Introduction to Python
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/PythonIntro.pdf
Python Summary
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/PythonSummary.pdf
Notes on Python
» http://www.nyu.edu/classes/jcf/g22.2110-
001/handouts/PythonNotes.html
80
Assignments & Readings
Readings
» Chapter Sections 6.1-6.5
Programming Assignment:
» See Programming Assignment #1 posted under “handouts” on the
course Web site
» Due on July 3, 2014
81
Next Session:
Subprograms:
» Functions and Procedures
» Parameter Passing
» Nested Procedures
» First-Class and Higher-Order Functions
82