Statement-Level Control Structures

Slides:



Advertisements
Similar presentations
ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Advertisements

Statement-Level Control Structures
CSCI 330: Programming Language Concepts Instructor: Pranava K. Jha Control Flow-II: Execution Order.
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
ICE1341 Programming Languages Spring 2005 Lecture #12 Lecture #12 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Chapter 8 Statement-Level Control Structures. 1-2 Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 8 Topics Introduction Selection Statements Iterative.
(8.1) COEN Control Structures  Control structure general issues  Compound statements  Selectors (conditional structures) – single – two-way –
ISBN Chapter 8 Statement-Level Control Structures.
The Flow of Control Among Statements.  Selection Statements  Iterative Statements  Unconditional Branching  Guarded Commands.
ICE1341 Programming Languages Spring 2005 Lecture #14 Lecture #14 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Chapter 8 Statement-Level Control Structure. Introduction Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program statements.
ISBN Chapter 8 Statement-Level Control Structures.
ISBN Chapter 8 Statement-Level Control Structures.
ISBN Chapter 8 Statement-Level Control Structures.
Controlling Program Flows
Chapter 8 (Control Structure) Slide 1 Control Structures Control structures are used by the programmer to incorporate the desired sequence of execution.
Statement-Level Control Structures Sections 1-4
ISBN Chapter 8 Statement-Level Control Structures.
CSE 452: Programming Languages Expressions and Control Flow.
1 Chapter 8 Statement-Level Control Structures In Chapter 7, the flow of control within expressions, which is governed by operator associativity and precedence.
ISBN Lecture 08 Statement-Level Control Structures.
ISBN Chapter 8 Statement-Level Control Structures.
COMP4730/2002/lec8/H.Melikian Statement-Level Control Structures Introduction Compound Statements Selection Statements Iterative Statements Unconditional.
Statement-Level Control Structures
1 Statement-Level Control Structures Levels of flow control Control Statements 1. Sequence 2. Selection 3. Iteration Unconditional branching Guarded commands.
Structure of Programming Language
9/20/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 06 Components of Programming Languages, Part III Reference: R.Sebesta,
ISBN Chapter 8 Statement-Level Control Structures Sections 1-4.
PLLab, NTHU,Cs2403 Programming Languages Expression and control structure Kun-Yuan Hsieh Programming Language Lab., NTHU.
Control Structures Programs have 4 basic control structures:
ISBN Chapter 8 Statement-Level Control Structures.
Chapter 8 Chapter 8 Control Structures. Control Structures  A control structure is a control statement and the statements whose execution it controls.
ISBN Chapter 8 Statement-Level Control Structures.
1 CS Programming Languages Class 11 September 26, 2000.
sequence of execution of high-level statements
Expressions and Statements. Expressions Literals and identifiers are expressions More complex expressions are built from simple expressions by the application.
第八章 敘述層級的控制結構 (Statement-Level Control Structures)
Chapter 8: Statement-Level Control Structures
Control Structures sequence of execution of high-level statements.
8-1 Statement-Level Control Structures Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions.
C HAPTER 8 Statement-Level Control Structures. CCSB314 Programming Language C HAPTER 8 T OPICS Introduction Selection Statements Iterative Statements.
April 16, ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)
Statement Level Flow of Control Iteration Structures Copyright © by Curt Hill.
Copyright © 1998 by Addison Wesley Longman, Inc. 1 Chapter 7 Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program statements.
1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control.
Chapter 8 © 2002 by Addison Wesley Longman, Inc Introduction - Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program.
W E E K F I V E Statement-Level Control Structures.
Structure of Programming Language Statements. Expression.
LECTURE 18 Control Flow. CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear.
W E E K F I V E Control Flow. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 8 Topics Introduction Selection Statements Iterative Statements.
Chapter 8 Statement-Level Control Structures. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 8 Topics Introduction Selection Statements.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 8 Statement-Level Control Structures. 2 Chapter 8 Topics  Introduction  Selection Statements  Iterative Statements  Unconditional Branching.
Def: A control structure is a control statement and
Structure of Programming Language
8.1 Introduction - Levels of Control Flow: 1. Within expressions
Dr. Vamsi Paruchuri University of Central Arkansas
Statement-Level Control Structures
Chapter 8: Control Structures
Statement-Level Control Structures
Statement-Level Control Structures
Control Structures In Text: Chapter 8.
Control Structures Programs utilize 4 basic control structures
Statement-Level Control Structures
Chapter8: Statement-Level Control Structures April 9, 2019
Statement-Level Control Structures
Statement-Level Control Structures
CSC215 Lecture Control Flow.
Chapter 8: Statement Level Control Structures
Presentation transcript:

Statement-Level Control Structures Chapter 8 Statement-Level Control Structures

Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions

Levels of Control Flow Within expressions Among program statements Among program units

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

Introduction Control Statements Selection among several alternative control flow paths Repeated execution of collections of statements Overall Design Issue What control statements should a language have, beyond selection and pretest logical loops?

Categories of Control Structures Introduction Definition: A control structure is a control statement and the statements whose execution it controls Categories of Control Structures Compound statements Selection statements Iteration statements Unconditional branching

Python uses indentation! Compound Statements Definition: A block is a compound statement, including data declarations, defining a new scope Some languages have specially delimited compound statements: begin ... end { ... } Some control constructs have built-in delimiters: repeat ... until Python uses indentation!

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

Two-Way Selection Statements Multiple Selection Constructs Design Issues The Control Expression Clause Form Nesting Selectors Multiple Selection Constructs Examples of Multiple Selectors Multiple Selection Using if

Two-Way Selection General form: if <control_expression> then <then_clause> else <else_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?

Two-Way Selection 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? Control Expressions Syntax: Parentheses? Data type?

Single statements or compound statements? Two-Way Selection Clause Form Single statements or compound statements? Single statement example: (FORTRAN) IF (<boolean_expr>) statement IF (.NOT.<condition>) GOTO 20 ... 20 CONTINUE Compound statement example: (ALGOL 60) if (<boolean_expr>) then <statement> else <statement>

Two-Way Selection Nested Selectors Example (Java) if ... ... else ... Which if gets the else? Java's static semantics rule: else goes with the nearest if

Two-Way Selection Nested Selectors Fortran 95, Ada – closing special words Examples (Ada) if ... then if ... then ... ... else end if ... else end if ... end if end if Advantages: flexibility and readability Modula-2 uses the same closing special word for all control structures: END This results in poor readability

Multiple Selection 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 should unrepresented selector expression values be handled, if at all? These questions are answered for each example

Early Multiple Selectors Multiple Selection Early Multiple Selectors FORTRAN arithmetic IF (a three-way selector) IF (<arithmetic-expression>) 10,20,30 10 ... ... GO TO 40 20 ... 30 ... 40 ...

Modern Multiple Selectors Pascal case case <expression> of <constant_list_1> : <statement_1>; ... <constant_list_n> : <statement_n> end Design choices 1. <expression> is any ordinal type int, boolean, char, enum 2. <statement_i> can be either single or compound 3. Only one segment can be executed per construct execution 4. Unrepresented <expression> not defined

Modern Multiple Selectors The C Langauges switch switch (<expression>) { case <const_expr_1> : <statement_1>; ... case <const_expr_n> : <statement_n>; [default: <statement_n+1>] } Design Choices 1. <expression> can be an integer type only 2. <statement_i> can be sequences 3. Many segments can be executed in one construct execution 4. The default clause is for unrepresented values (without it, the whole statement may do nothing)

Modern Multiple Selectors The Ada case statement case <expression> is 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

Multiple Selection Using if Some languages specifically extend the if statement, allowing some of the special words to be left out else-if sequences are replaced with a single special word elsif and the closing special word on the nested if is dropped Ada if Count < 10 then Bag1 := True; elsif Count < 100 then Bag2 := True; elsif Count < 1000 then Bag3 := True; end if; This is not easily modeled with a case statement, since each selector is a Boolean expression

Iterative Statements Counter-Controlled Loops Design Issues Fortran 95 Do Ada for C languages for Logically Controlled Loops Examples User-Located Loop Control Mechanisms Iteration Based on Data Structures

for Iteration Control Statements Iterative Statements Repeated execution of a statement or compound statement can be accomplished either by iteration or recursion Here we look at iteration -- recursion is unit-level control General Design Issues for Iteration Control Statements How is iteration controlled? Where is the control mechanism in the loop?

These questions are answered for each example Counter-Controlled Loops 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? These questions are answered for each example

Counter-Controlled Loops Fortran 95 Do <label> <var>=<start>,<finish>[,<stepsize>] [<name>:] Do <var>=<start>,<finish>[,<stepsize>] ... End Do [<name>] Design Choices 1. <var> must be Integer 2. After execution, <var> has its last value 3. <var> cannot be changed in the loop 4. Loop parameters can be changed in the loop Notes: - Cannot branch into either Do - <stepsize> can be any value but zero - Loop parameters can be expressions

Counter-Controlled Loops Ada for <var> in [reverse] <discrete_range> loop ... end loop Design Choices 1. Type of <var> is that of <discrete_range>; its scope is the loop body 2. <var> does not exist outside the loop 3. <var> cannot be changed in the loop, <discrete_range> can be changed in the loop 4. <discrete_range> is evaluated only once, so changing it does not affect loop control Note: Cannot branch into the loop body

Counter-Controlled Loops C Languages for ([<exp1>];[<exp2>];[<exp3>])<statement> Design Choices 1. There is no explicit loop variable 2. The loop variable (if there is one) has its latest value 3. Everything can be changed in the loop 4. <exp1> is evaluated once, but the other two are evaluated with each iteration Notes: - The expressions can be statements or statement sequences for (i=0,j=10;j==i;i++)... - If the second expression is absent, it is an infinite loop

Counter-Controlled Loops The loop statement of the C languages is the most flexible, but there are differences mostly based on the while loop C99,C++ for: The control expression is coercised Boolean The initial expression can include variable definitions (scope is from the definition to the end of the loop body) Can branch into them Java,C# for: The control expression must be Boolean Branching into the loop? Java no C# yes

Logically-Controlled Loops Design Issues Should the language have a pretest loop or a posttest loop or both? Should this be a special case of the counter-controlled loop or a completely separate statement?

Logically-Controlled Loops Language Examples C Languages have both while-do and do-while Branching into either loop construct? C,C++,C# yes Java no Ada has a pretest version, but no posttest Fortran 95 has neither Perl has two pretest logical loops, while and until, but no posttest logical loop

User-Located Loop Controls Design Issues Should the conditional be part of the exit? Should control be transferable, conditionally or unconditionally, out of more than one nested loop?

User-Located Loop Controls Language Examples Ada conditional or unconditional, for any loop, any number of levels for ... loop ... exit [when ...] end loop LOOP1: while ... loop ... LOOP2: for ... loop exit LOOP1 [when ...] end loop LOOP2; end loop LOOP1;

User-Located Loop Controls Language Examples C Languages break Unconditional, for any loop or switch C,C++ one level only Java,Perl,C# multiple levels, by labels continue Skips the remainder of this iteration, but does not exit the loop Fortran 95 Exit, Cycle Unconditional for any loop, any number of levels

Data Structure Iteration Concept Use the order and number of elements of some data structure to control iteration Control Mechanism A function call (the iterator) that returns either the next element in a chosen order, if there is one, or else exits the loop Languages Specific structures: Perl, PHP, JavaScript, C# Can be modeled in most languages by functions, easily so in object-oriented languages

Data Structure Iteration Examples C,C++ traversing a linked list using pointers for (p=hdr; p; p=next(p)){...} C# String[] strList = {″Bob″,″Carol″, ...}; ... foreach (String name in strList) System.Console.WriteLine(″Name: {0}″,name); The foreach statement iterates the elements of any collection that implements IEnumerable

Data Structure Iteration Examples Perl has a built-in iterator for arrays and hashes foreach $name (@names) { print $name } PHP has predefined iterators to access its arrays current points at one element of the array next moves current to the next element prev moves current to the previous element reset moves current to the first element

Data Structure Iteration User-defined Iteration C++ iterators are often implemented as friend functions or as separate iterator classes Java objects of a class implementing the Collection interface can be iterated with an implementation of the Iterator interface - next() moves the pointer into the collection - hasNext() is a predicate - remove() deletes an element C# can iterate any collection implementing the IEnumerate interface - MoveNext() moves the pointer in the collection - Reset() moves the pointer to the beginning - Current is the current element - Can also use foreach to iterate

Unconditional Branching General Syntax goto <Label> Disadvantage readability Advantage flexibility Notes: All control structures can be built with goto and a selector Some languages do not have them Modula-2, Java Loop exit statements are camouflaged goto’s - they are severely restricted - not harmful to readability

“Go To Statement Considered Harmful” ...the quality of programmers is a decreasing function of the density of go to statements in the programs they produce.... ...the go to statement should be abolished from all "higher level" programming languages... The go to statement as it stands is just too primitive; it is too much an invitation to make a mess of one's program.... Dijkstra, Edsger W., Go To Statement Considered Harmful. Communications of the ACM, Vol. 11, No. 3, March 1968, pp. 147-148.

“Go To Statement Considered Harmful” Dijkstra’s remark about the undesirability of the goto statement was not new, and was not final ! 1959 Heinz Zemanek expressed doubts 1966 Wirth and Hoare “[multiple selection] mirrors the dynamic structure of a program more clearly than goto statements" 1966 Guiseppe Jacopini proved the (logical) superfluousness of the goto statement 1968 Dijkstra Communications of the ACM 1974 Knuth argued that there were occasions when the efficiency of the goto outweighed its harm to readability 1978 Kernighan and Ritchie called the goto “inifinitely abusable,” but included it in C anyway

'GOTO Considered Harmful' Considered Harmful In computing and related disciplines, considered harmful is a phrase used in the titles of diatribes and other critical essays (there are more than 65 such works). The March 1987 CACM contained a criticism of Dijkstra's letter under the title 'GOTO Considered Harmful' Considered Harmful. The May 1987 CACM printed further replies, both for and against, under the title '"GOTO Considered Harmful" Considered Harmful' Considered Harmful?. Dijkstra's own response to this controversy was titled On a somewhat disappointing correspondence.

http://www.considered-harmful.org/

Guarded Commands Edsger Dijkstra (1975, 1976) Purpose to support a new programming methodology (verification during program development) Idea if the order of evaluation is not important, the program should not specify one Used in concurrent programming: CSP, Ada Used in function definitions: Haskell

Guarded Commands Selection Syntax: if <boolean> -> <statement> [] <boolean> -> <statement> ... fi [] is called a fatbar Semantics: When this construct is reached: Evaluate all boolean expressions If more than one are true, choose one nondeterministically If none are true, runtime error

Selection Guarded Command Flow Chart

Guarded Commands Selection examples (text pp. 367-368) if i = 0 -> sum := sum + i [] i > j -> sum := sum + j [] j > i -> sum := sum + i fi if x >= y -> max := x [] y >= x -> max := y

Guarded Commands Loop Syntax: do <boolean> -> <statement> [ ] <boolean> -> <statement> ... od Semantics: For each iteration: Evaluate all boolean expressions If more than one are true, choose one nondeterministically; then start loop again If none are true, exit loop

Loop Guarded Command Flow Chart

arrange the values of q1, q2, q3, and q4 so that Guarded Commands Loop example (text p. 369) arrange the values of q1, q2, q3, and q4 so that q1 <= q2 <= q3 <= q4 do q1 > q2 -> temp := q1; q1 := q2; q2 := temp [] q2 > q3 -> temp := q2; q2 := q3; q3 := temp [] q3 > q4 -> temp := q3; q3 := q4; q3 := temp od

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

Conclusions Choice of control statements beyond selection and logical pretest loops is a trade-off between language size and writability