Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

Similar documents
Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

Statement level control structures

Chapter 8. Statement-Level Control Structures

Ch. 7: Control Structures

Iterative Statements. Iterative Statements: Examples. Counter-Controlled Loops. ICOM 4036 Programming Languages Statement-Level Control Structure

Chapter 8. Statement-Level Control Structures

Chapter 8. Statement-Level Control Structures ISBN

Chapter 8. Statement-Level Control Structures

Flow of Control Execution Sequence

Chapter 8 Statement-Level Control Structures

Chapter 8 Statement-Level Control Structure

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

LECTURE 18. Control Flow

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Chapter 7 Control I Expressions and Statements

Relational Expressions. Boolean Expressions. Boolean Expressions. ICOM 4036 Programming Languages. Boolean Expressions

Programming Languages Semantics

G Programming Languages - Fall 2012

CSc 520 Principles of Programming Languages. 26 : Control Structures Introduction

Ordering Within Expressions. Control Flow. Side-effects. Side-effects. Order of Evaluation. Misbehaving Floating-Point Numbers.

Control Flow COMS W4115. Prof. Stephen A. Edwards Fall 2006 Columbia University Department of Computer Science

More Examples. Lecture 24: More Scala. Higher-Order Functions. Control Structures

Lecture 9: Control Flow

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

int foo() { x += 5; return x; } int a = foo() + x + foo(); Side-effects GCC sets a=25. int x = 0; int foo() { x += 5; return x; }

Statement-Level Control Structures

Statement-Level Control Structures

Control Flow. Stephen A. Edwards. Fall Columbia University

COP4020 Programming Languages. Control Flow Prof. Robert van Engelen

Imperative Programming Languages (IPL)

Lecture 4. CS118 Term planner. The simple if statement. Control flow: selection. The if... else statement cont... The if... else statement.

Compiler Construction

Principles of Programming Languages Lecture 22

Lecture 15: Iteration and Recursion

SE352b: Roadmap. SE352b Software Engineering Design Tools. W3: Programming Paradigms

Flow Control. CSC215 Lecture

Chapter 5 Names, Binding, Type Checking and Scopes

Compiler Construction

Compiler Construction

Compiler Construction

Compiler Construction

Defining Program Syntax. Chapter Two Modern Programming Languages, 2nd ed. 1

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

Introduction. A. Bellaachia Page: 1

Qualifying Exam in Programming Languages and Compilers

Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

Introduction. C provides two styles of flow control:

5. Control Statements

ECE 122. Engineering Problem Solving with Java

Programming Languages, Summary CSC419; Odelia Schwartz

General Concepts. Abstraction Computational Paradigms Implementation Application Domains Influence on Success Influences on Design

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

Introduction to Programming Using Java (98-388)

Decision Making -Branching. Class Incharge: S. Sasirekha

Chapter 6 Control Flow. June 9, 2015

Quick Reference Guide

Data Types. Outline. In Text: Chapter 6. What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 5-1. Chapter 6: Data Types 2

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Following is the general form of a typical decision making structure found in most of the programming languages:

Programming for Engineers Iteration

Principles of Programming Languages. Lecture Outline

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Chapter 5. Names, Bindings, and Scopes

Chapter 6. Structured Data Types. Topics. Structured Data Types. Vectors and Arrays. Vectors. Vectors: subscripts

Data Types In Text: Ch C apter 6 1

Compiler Construction

Languages and Compilers (SProg og Oversættere)

Expressions and Statements. Department of CSE, MIT, Manipal

CS1100 Introduction to Programming

NOTE: Answer ANY FOUR of the following 6 sections:

Compiler Construction

8. Control statements

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

MIDTERM EXAMINATION - CS130 - Spring 2003

520 Principles of Programming Languages. Arithmetic. Variable Declarations. 19: Pascal

Page # Expression Evaluation: Outline. CSCI: 4500/6500 Programming Languages. Expression Evaluation: Precedence

1 Lexical Considerations

Iteration. Side effects

Answer: Early binding generally leads to greater efficiency (compilation approach) Late binding general leads to greater flexibility

Lexical Considerations

CS 199 Computer Programming. Spring 2018 Lecture 5 Control Statements

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Imperative Programming

Software Engineering using Formal Methods

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

Expressions vs statements

CSC 533: Organization of Programming Languages. Spring 2005

Review of the C Programming Language

9/7/17. Outline. Name, Scope and Binding. Names. Introduction. Names (continued) Names (continued) In Text: Chapter 5

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

Lexical Considerations

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Structure of Programming Languages Lecture 5

Formal Specification and Verification

CS 314 Principles of Programming Languages

The PCAT Programming Language Reference Manual

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Transcription:

Control Structures In Text: Chapter 8 1 Control structures Selection One-way Two-way Multi-way Iteration Counter-controlled Logically-controlled Gotos Guarded statements Outline Chapter 8: Control Structures 2 7-1

Levels of Control Flow Within expressions Among program statements Among program units Chapter 8: Control Structures 3 Control Structures A control structure is a control statement and the statements whose execution it controls Overall Design Question: What control statements should a language have, beyond selection and pretest logical loops? Single entry/single exit are highly desirable a lesson learned from structured programming Chapter 8: Control Structures 4 7-2

Design Issues: Selection Statements What is the form and type of the control expression? What is the selectable segment form? single statement, statement sequence, compound statement How should the meaning of nested selectors be specified? Chapter 8: Control Structures 5 Single-Way Selection One-way if statement FORTRAN IF: IF (boolean_expr) statement Problem: can select only a single statement; to select more, a goto must be used IF (.NOT. condition) GOTO 20 20 CONTINUE Chapter 8: Control Structures 6 7-3

Two-Way Selection if-then-else statement ALGOL 60 if: if (boolean_expr) then statement else statement The statements could be single or compound begin end A block is a compound statement that can define a new scope (with local variables) Chapter 8: Control Structures 7 Pascal: if then if then else Nested Selectors Which then gets the else? Pascal's rule: else goes with the nearest then Chapter 8: Control Structures 8 7-4

Disallowing Direct Nesting ALGOL 60 s solution disallows direct nesting if then begin if then else end if then begin if then end else Chapter 8: Control Structures 9 Closing Reserved Words FORTRAN 77, Ada, Modula-2 solution closing special words In Ada: if then if then else end if end if end if Advantage: flexibility and readability if then if then end if else Modula-2 uses END for all control structures This results in poor readability Chapter 8: Control Structures 10 7-5

Multiple Selection Constructs Design Issues: What is the form and type of the control expression? What segments are selectable (single, compound, sequential)? Is the entire construct encapsulated? Is execution flow through the structure restricted to include just a single selectable segment? What about unrepresented expression values? Chapter 8: Control Structures 11 Early Multiple Selectors: FORTRAN arithmetic IF (a three-way selector) IF (arithmetic expression) N1, N2, N3 Disadvantages: Not encapsulated selectable segments could be anywhere FORTRAN computed GOTO GO TO (L1, L2,, Ln), exp goes to first label if exp=1, second if exp=2, etc. if exp < 1 or exp > n, no effect must still jump out of segment Chapter 8: Control Structures 12 7-6

Pascal case Modern Multiple Selectors from Hoare's contribution to ALGOL W case expression of constant_list_1 : statement_1; constant_list_n : statement_n end Chapter 8: Control Structures 13 Case: Pascal Design Choices Expression is any ordinal type int, boolean, char, enum Segments can be single or compound Construct is encapsulated Only one segment can be executed per execution of the construct In Wirth's Pascal, result of an unrepresented control expression value is undefined Many dialects now have otherwise or else clause Chapter 8: Control Structures 14 7-7

C/C++ Switch switch (expression) { constant_expression_1 : statement_1; constant_expression_n : statement_n; [default: statement_n+1] } Design Choices (for switch): Control expression can be only an integer type Selectable segments can be statement sequences or blocks Construct is encapsulated Any number of segments can be executed in one execution of the construct (reliability vs. flexibility) Default clause for unrepresented values Chapter 8: Control Structures 15 Case: Ada Design Choices case expression is when constant_list_1 => statement_1; when constant_list_n => statement_n; end Similar to Pascal, except Constant lists can include: Subranges: 10..15 Multiple choices: 1..5 7 15..20 Lists of constants must be exhaustive (more reliable) Often accomplished with others clause Chapter 8: Control Structures 16 7-8

Multi-Way If Statements Multiple selectors can appear as direct extensions to two-way selectors, using else-if clauses ALGOL 68, FORTRAN 77, Modula-2, Ada Ada: if then elsif then elsif then else end if Far more readable than deeply nested if's Allows a boolean gate on every selectable group Chapter 8: Control Structures 17 Iterative Statements The repeated execution of a statement or compound statement is accomplished either by iteration or recursion Here we look at iteration, because recursion is unit-level control General design issues for iteration control statements: How is iteration controlled? Where is the control mechanism in the loop? Two common strategies: counter-controlled, and logically-controlled Chapter 8: Control Structures 18 7-9

Counter-Controlled Loops Design Issues: What is the type (ordinal vs. real) and scope of the loop variable? What is the value of the loop variable at loop termination? Should it be legal for the loop variable or loop parameters to be changed in the loop body? If so, does the change affect loop control? Should the loop parameters be evaluated only once, or once for every iteration? Chapter 8: Control Structures 19 FORTRAN DO Loops FORTRAN 77 and 90 Syntax: DO label var = start, finish [, stepsize] Stepsize can be any value but zero Parameters can be expressions Design choices: Loop var can be INTEGER, REAL, or DOUBLE Loop var always has its last value Loop parameters are evaluated only once The loop var cannot be changed in the loop, but the parameters can; because they are evaluated only once, it does not affect loop control Chapter 8: Control Structures 20 7-10

FORTRAN 90 s Other DO Syntax: [name:] DO variable = initial, terminal [, stepsize] END DO [name] Loop var must be an INTEGER Chapter 8: Control Structures 21 ALGOL 60 For Loop Syntax: for var := <list_of_stuff> do statement where <list_of_stuff> can have: list of expressions expression step expression until expression expression while boolean_expression for index := 1 step 2 until 50, 60, 70, 80, index + 1 until 100 do (index = 1, 3, 5, 7,, 49, 60, 70, 80, 81, 82,, 100) Chapter 8: Control Structures 22 7-11

ALGOL 60 For Design Choices Control expression can be int or real; its scope is whatever it is declared to be Control var has its last assigned value after loop termination The loop var cannot be changed in the loop, but the parameters can, and when they are, it affects loop control Parameters are evaluated with every iteration, making it very complex and difficult to read Chapter 8: Control Structures 23 Pascal For Loop Syntax: for var := initial (to downto) final do statement Design Choices: Loop var must be an ordinal type of usual scope After normal termination, loop var is undefined The loop var 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 Chapter 8: Control Structures 24 7-12

Ada For Loop Syntax: for var in [reverse] discrete_range loop end loop Design choices: Type of the loop var is that of the discrete range (e.g., [1..100] ); its scope is the loop body (it is implicitly declared) The loop var does not exist outside the loop The loop var cannot be changed in the loop, but the discrete range can; it does not affect loop control The discrete range is evaluated just once Chapter 8: Control Structures 25 C For Loop Syntax: for ([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 Chapter 8: Control Structures 26 7-13

C For Loop Design Choices There is no explicit loop variable Everything can be changed in the loop Pretest The first expression is evaluated once, but the other two are evaluated with each iteration This loop statement is the most flexible Chapter 8: Control Structures 27 C++ & Java For Loops Differs from C in two ways: The control expression can also be Boolean The initial expression can include variable definitions; scope is from the definition to the end of the body of the loop Java is the same, except the control expression must be Boolean Chapter 8: Control Structures 28 7-14

Logically-Controlled Loops Design Issues: Pretest or post-test? Should this be a special case of the counting loop statement, or a separate statement? Chapter 8: Control Structures 29 Logic Loops: Examples Pascal: separate pretest and posttest logical loop statements while-do and repeat-until C and C++: also have both while - do and do - while Java: like C, except the control expression must be Boolean (and the body can only be entered at the beginning Java has no goto) Ada: a pretest version, but no post-test FORTRAN 77 and 90: have neither Chapter 8: Control Structures 30 7-15

User-Located Loop Controls Statements like break or continue Design issues: Should the conditional be part of the exit? Should the mechanism be allowed in logicallyor counter-controlled loops? Should control be transferable out of more than one loop? Chapter 8: Control Structures 31 User-Located Controls: Ada Can be 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; Chapter 8: Control Structures 32 7-16

User-Loc. Controls: More Examples C, C++, Java: Break: unconditional; for any loop or switch; one level only (except Java) Continue: skips the remainder of this iteration, but does not exit the loop FORTRAN 90: EXIT: Unconditional; for any loop, any number of levels CYCLE: same as C's continue Chapter 8: Control Structures 33 Iteration Based on Data Structures Lets user specify range of values over which a loop iterates (CLU). for (ptr = root; ptr == nul; traverse(ptr)) { } for i in `ls *` do od Chapter 8: Control Structures 34 7-17

Unconditional Branching (GOTO) Problem: readability Some languages do not have them: e.g., Modula-2 and Java They require some kind of statement label Label forms: Unsigned int constants: Pascal (with colon), FORTRAN (no colon) Identifiers with colons: ALGOL 60, C, C++ Identifiers in << >>: Ada Chapter 8: Control Structures 35 Variables as labels: PL/I Can store a label value in a variable Can be assigned values and passed as parameters Highly flexible, but make programs impossible to read and difficult to implement Chapter 8: Control Structures 36 7-18

Guarded Commands (Dijkstra, 1975) Purpose: to support a new programming methodology verification during program development Also useful for concurrency Two guarded forms: Selection (guarded if) Iteration (guarded while) Chapter 8: Control Structures 37 Guarded Selection if <boolean> -> <statement> [] <boolean> -> <statement> [] <boolean> -> <statement> fi Semantics: when this construct is reached, Evaluate all boolean expressions If more than one are true, choose one nondeterministically If none are true, it is a runtime error Idea: if the order of evaluation is not important, the program should not specify one See book examples (p. 343) Chapter 8: Control Structures 38 7-19

Guarded Iteration do <boolean> -> <statement> [] <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 See book example (p. 344) Chapter 8: Control Structures 39 Choice of Control Statements Beyond selection and logical pretest loops, choice is a trade-off between: Language size Readability Writability Chapter 8: Control Structures 40 7-20