Presentation is loading. Please wait.

Presentation is loading. Please wait.

9/20/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 06 Components of Programming Languages, Part III Reference: R.Sebesta,

Similar presentations


Presentation on theme: "9/20/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 06 Components of Programming Languages, Part III Reference: R.Sebesta,"— Presentation transcript:

1

2 9/20/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 06 Components of Programming Languages, Part III Reference: R.Sebesta, Chapter 8

3 9/20/2015Assoc. Prof. Stoyan Bonev2 Lecture Contents: Statement  Level Control Structures –Compound Statements –Selection Statements –Iterative Statements Guarded Commands (after E.Dijkstra)

4 9/20/2015Assoc. Prof. Stoyan Bonev3 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)

5 9/20/2015Assoc. Prof. Stoyan Bonev4 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.

6 9/20/2015Assoc. Prof. Stoyan Bonev5 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.

7 9/20/2015Assoc. Prof. Stoyan Bonev6 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”

8 9/20/2015Assoc. Prof. Stoyan Bonev7 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 goto  less programming.

9 9/20/2015Assoc. Prof. Stoyan Bonev8 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)

10 9/20/2015Assoc. Prof. Stoyan Bonev9 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

11 9/20/2015Assoc. Prof. Stoyan Bonev10 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.

12 Compound statements

13 9/20/2015Assoc. Prof. Stoyan Bonev12 Compound Statements Method to form statement collections. CS allow a collection of statements to abstract as a single statement. AlgolPascalC-like beginBEGIN{ stmt_1; stmt_1; stmt_1;......... stmt_n; stmt_n stmt_n; endEND} If CS contains definition/declaration, it’s a block. AlgolC-like,Perl,JavaScript,PHP begin{ integer index,count; int index,count;...... end}

14 9/20/2015Assoc. Prof. Stoyan Bonev13 Compound Statements Syntax diagram illustrates compound statement. C-like begin stmt_1;... stmt_n; End ::= begin { ; }* end

15 9/20/2015Assoc. Prof. Stoyan Bonev14 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;... }

16 Selection statements

17 9/20/2015Assoc. Prof. Stoyan Bonev16 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

18 9/20/2015Assoc. Prof. Stoyan Bonev17 Selection If/Then structure (single selection) T F If/Then/Else structure (double selection) T F... (multiple selection)

19 9/20/2015Assoc. Prof. Stoyan Bonev18 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?

20 9/20/2015Assoc. Prof. Stoyan Bonev19 VBasic selection statements include If condition Then statement sequence End If If condition Then statement sequence1 Else statement sequence2 End If

21 9/20/2015Assoc. Prof. Stoyan Bonev20 C/C++ selection statements include if (expression) statement sequence if (expression) statement sequence1 else statement sequence2

22 9/20/2015Assoc. Prof. Stoyan Bonev21 One-Way & Two-Way Selector Syntax diagram illustrates selector stmt

23 9/20/2015Assoc. Prof. Stoyan Bonev22 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

24 9/20/2015Assoc. Prof. Stoyan Bonev23 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)

25 9/20/2015Assoc. Prof. Stoyan Bonev24 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) { result = 0; } } } else { else { result = 1; result = 1; } } }

26 9/20/2015Assoc. Prof. Stoyan Bonev25 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?

27 9/20/2015Assoc. Prof. Stoyan Bonev26 Multiple Selectors - Examples Early versions (Fortran) –Arithmetic IF IF ( ) 10, 20, 30 –Computed GOTO GOTO (,, … ),

28 9/20/2015Assoc. Prof. Stoyan Bonev27 Multiple Selectors - Examples Visual Basic Select Case JobClass Case 1 Bonus = salary * 0.1 Case 2 Bonus = salary * 0.09 Case 3, 4 Bonus = salary * 0.075 Case 5 To 8 Bonus = salary * 0.05 Case Is > 8 Bonus = salary * 0.02 Case Else Bonus = 0 End Select

29 9/20/2015Assoc. Prof. Stoyan Bonev28 Multiple Selectors - Examples C, C++, Java switch ( ) { case : ;... case : ; [ default: ; ] } ;

30 9/20/2015Assoc. Prof. Stoyan Bonev29 Multiple Selectors - Examples Syntax diagram illustrates selector stmt.

31 9/20/2015Assoc. Prof. Stoyan Bonev30 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

32 9/20/2015Assoc. Prof. Stoyan Bonev31 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

33 9/20/2015Assoc. Prof. Stoyan Bonev32 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”); }

34 9/20/2015Assoc. Prof. Stoyan Bonev33 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

35 9/20/2015Assoc. Prof. Stoyan Bonev34 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;

36 9/20/2015Assoc. Prof. Stoyan Bonev35 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;

37 Iterative statements

38 9/20/2015Assoc. Prof. Stoyan Bonev37 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

39 9/20/2015Assoc. Prof. Stoyan Bonev38 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?

40 9/20/2015Assoc. Prof. Stoyan Bonev39 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

41 9/20/2015Assoc. Prof. Stoyan Bonev40 The Do stmt of Fortran 95 Formal syntax: Do label variable = initial, terminal [,stepsize] Examples: Do 100 I = 1,20,1... 100 Continue

42 9/20/2015Assoc. Prof. Stoyan Bonev41 For … Next Loop Statement of VBasic: For counter = initVal To endVal [Step incVal]... One or more VB statements... Next [counter]

43 9/20/2015Assoc. Prof. Stoyan Bonev42 The for stmt of C-like PL Formal syntax: for( ; ; ) ; 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”;

44 9/20/2015Assoc. Prof. Stoyan Bonev43 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.

45 9/20/2015Assoc. Prof. Stoyan Bonev44 For loop converted to while for( ; ; ) ; ; while ( ) { ; }

46 9/20/2015Assoc. Prof. Stoyan Bonev45 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

47 9/20/2015Assoc. Prof. Stoyan Bonev46 Logic Loops - Syntax Pretest loop while ( ) Flow chart and syntax diagram Posttest loop do while ( ) Flow chart

48 9/20/2015Assoc. Prof. Stoyan Bonev47 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);

49 9/20/2015Assoc. Prof. Stoyan Bonev48 Do Loops in VBasic Do While boolean expression statements Loop ------------------------------------------ Do Until boolean expression statements Loop ------------------------------------------ Do statements Loop While boolean expression ------------------------------------------ Do statements Loop Until boolean expression ------------------------------------------ Do statements Loop

50 9/20/2015Assoc. Prof. Stoyan Bonev49 Do Loops in VBasic Pretest loops ----------------------------------------- Do While boolean expression statements Loop ----------------------------------------- Do Until boolean expression statements Loop -----------------------------------------

51 9/20/2015Assoc. Prof. Stoyan Bonev50 Do Loops in VBasic Posttest loops ----------------------------------------- Do statements Loop While boolean expression ----------------------------------------- Do statements Loop Until boolean expression -----------------------------------------

52 9/20/2015Assoc. Prof. Stoyan Bonev51 Do Loops in VBasic Infinite /endless/ loops ----------------------------------------- Do statements Loop -----------------------------------------

53 9/20/2015Assoc. Prof. Stoyan Bonev52 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.

54 9/20/2015Assoc. Prof. Stoyan Bonev53 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

55 9/20/2015Assoc. Prof. Stoyan Bonev54 Loops – Practical Application Iterative processing concept (intro for beginners) if (there are any steps to repeat) { loop required; } else { no loop required }

56 9/20/2015Assoc. Prof. Stoyan Bonev55 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; or use End File controlled loop;or use Input Validation loop;or use General conditional loop; }

57 9/20/2015Assoc. Prof. Stoyan Bonev56 Loop Patterns Sentinel Controlled Loops 1. 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 Loops 1. 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.

58 9/20/2015Assoc. Prof. Stoyan Bonev57 Example of Sentinel Controlled Loop #define SENTINEL (-99)... int sum=0, var; cout > var; while (var != SENTINEL) { sum += var;cin >> var; } cout << sum;

59 9/20/2015Assoc. Prof. Stoyan Bonev58 Example of End File (End of Data) Controlled Loop int var, sum=0; cout > var; while ( !(cin.eof()) ) { sum+=var; cout << Enter new value:"; cin >> var; } cout << "\n\nSum=" << sum ;

60 9/20/2015Assoc. Prof. Stoyan Bonev59 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; }

61 9/20/2015Assoc. Prof. Stoyan Bonev60 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.

62 9/20/2015Assoc. Prof. Stoyan Bonev61 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.

63 9/20/2015Assoc. Prof. Stoyan Bonev62 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.

64 9/20/2015Assoc. Prof. Stoyan Bonev63 Exercise 4a Components of Programming Languages. Part III. Practical Statement  Level Control Structures Assignments under discussion are based on lecture 4.

65 9/20/2015Assoc. Prof. Stoyan Bonev64 Task 1 Using 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: xsqr(x)cube(x) displays Fahrenheit  Celsius table in a range and format chosen by the student. The relation Celsius/Fahrenheit is Celsius = 5 / 9 * (Fahrenheit – 32)

66 9/20/2015Assoc. Prof. Stoyan Bonev65 Reminder Quiz #1 on Components of PL

67 ISBN 0-321-49362-1 Chapter 8 Statement-Level Control Structures

68 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

69 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)

70 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

71 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?

72 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

73 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 clause 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?

74 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

75 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 "

76 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

77 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

78 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

79 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

80 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?

81 Copyright © 2009 Addison-Wesley. All rights reserved.1-80Copyright © 2009 Addison-Wesley. All rights reserved.1-80 Multiple-Way Selection: Examples C, C++, and Java switch (expression) { case const_expr_1: stmt_1; … case const_expr_n: stmt_n; [default: stmt_n+1] }

82 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 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)

83 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

84 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

85 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 ( | )

86 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

87 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

88 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

89 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?

90 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?

91 Copyright © 2009 Addison-Wesley. All rights reserved.1-90Copyright © 2009 Addison-Wesley. All rights reserved.1-90 Iterative Statements: Examples FORTRAN 95 syntax DO label var = start, finish [, stepsize ] Stepsize can be any value but zero Parameters can be expressions Design choices: 1. Loop variable must be INTEGER 2. 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

92 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

93 Copyright © 2009 Addison-Wesley. All rights reserved.1-92Copyright © 2009 Addison-Wesley. All rights reserved.1-92 Iterative Statements: Examples Ada for 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

94 Copyright © 2009 Addison-Wesley. All rights reserved.1-93Copyright © 2009 Addison-Wesley. All rights reserved.1-93 Iterative Statements: Examples C-based languages 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 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

95 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 Boolean 2.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

96 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

97 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?

98 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 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

99 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

100 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?

101 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

102 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)){ }

103 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

104 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

105 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

106 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

107 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

108 Copyright © 2009 Addison-Wesley. All rights reserved.1-107Copyright © 2009 Addison-Wesley. All rights reserved.1-107 Selection Guarded Command Form if -> [] ->... [] -> 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

109 Copyright © 2009 Addison-Wesley. All rights reserved.1-108Copyright © 2009 Addison-Wesley. All rights reserved.1-108 Loop Guarded Command Form do -> [] ->... [] -> 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

110 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

111 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

112 Thank You for Your attention


Download ppt "9/20/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 06 Components of Programming Languages, Part III Reference: R.Sebesta,"

Similar presentations


Ads by Google