April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages...

18
April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages Programming Languages (ICE 1341) (ICE 1341) Lecture #14 Lecture #14 April 16, 2004 In-Young Ko iko .AT. i cu . ac.kr Information and Communications University (ICU)

Transcript of April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages...

Page 1: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Programming LanguagesProgramming Languages(ICE 1341)(ICE 1341)

Lecture #14Lecture #14 April 16, 2004

In-Young Koiko .AT. icu.ac.kr

Information and Communications University (ICU)

Page 2: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 2 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Review of the Previous LecturesReview of the Previous Lectures

Language Evaluation CriteriaLanguage Evaluation Criteria Describing Syntax and SemanticsDescribing Syntax and Semantics Names and BindingsNames and Bindings Data TypesData Types ExpressionsExpressions

Page 3: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 3 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Control StructuresControl Structures

Control Structure: a Control Structure: a control statementcontrol statement and the and the statements whose execution it controlsstatements whose execution it controls Selection StatementsSelection Statements – if, switch – if, switch Iterative StatementsIterative Statements – do, for, while, …– do, for, while, … Unconditional BranchingUnconditional Branching – goto– goto Guarded CommandsGuarded Commands – nondeterministic if– nondeterministic if

Levels of Control FlowLevels of Control Flow Within expressionsWithin expressions Among program statementsAmong program statements Among program unitsAmong program units

Page 4: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 4 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Selection StatementsSelection Statements

SSelection election SStatementtatement: a: a means of means of choosing between choosing between two or more two or more execution execution pathspaths in a programin a program

Two general categoriesTwo general categories: : Two-way selectorsTwo-way selectors, , Multiple-Multiple-way selectorsway selectors

Design IssuesDesign Issues of Two-Way Selectors of Two-Way Selectors What is the What is the formform and and typetype of the of the control expressioncontrol expression?? HowHow are the are the thenthen and and elseelse clauses clauses specified? specified? How should the How should the meaningmeaning of of nested selectorsnested selectors be specified? be specified?

if (sum == 0)if (sum == 0)if (count == 0)if (count == 0) result = 0;result = 0;

elseelseresult = 1;result = 1;

IF (SUM .NE. 0) GOTO 10IF (SUM .NE. 0) GOTO 10 IF (COUNT .NE. 0) GOTO 20IF (COUNT .NE. 0) GOTO 20 RESULT = 0RESULT = 0 GOTO 20GOTO 2010 RESULT = 110 RESULT = 120 CONTINUE20 CONTINUE

Page 5: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 5 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Nested Two-Way SelectorsNested Two-Way Selectors

ALGOL 60ALGOL 60 –– disallow disallow direct nestingdirect nesting

if ... thenif ... then beginbegin if ...if ...tthenhen ...... endend else ...else ...

JavaJava – – elseelse goes goes with the with the nearestnearest ififif ... if ...

ifif ... ... elseelse ... ...

FORTRANFORTRAN 90 90 and and AdaAda – closing special words– closing special words

ifif ... then ... then ifif ... then ... then ...... end ifend if elseelse ...... end ifend if

Page 6: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 6 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Multiple Selection Statements (1)Multiple Selection Statements (1)

Design IssuesDesign Issues::1. What is the form and type of 1. What is the form and type of

the the control expressioncontrol expression??

2. How are the 2. How are the selectable selectable segmentssegments specified? specified?

3. Is 3. Is execution flowexecution flow through through the structure restricted to the structure restricted to include just a single include just a single selectable segment?selectable segment?

4. What is done about 4. What is done about unrepresented expressionunrepresented expression values?values?

switch (month) {switch (month) { case 3:case 3: case 4:case 4: case 5: season = "Spring";case 5: season = "Spring";

break;break; case 6:case 6: case 7:case 7: case 8: season = "Summer"; case 8: season = "Summer";

break;break; case 9:case 9: case 10: case 10: case 11: season = "Fall"; case 11: season = "Fall";

break;break; default: season = "Winter";default: season = "Winter";

break;break;}}

* AW Lecture Notes

Page 7: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 7 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Multiple Selection Statements (2)Multiple Selection Statements (2)

Design Design Choices (C Switch)Choices (C Switch)::1. 1. Control eControl expression can be xpression can be

only an only an integer typeinteger type

2. Selectable segments can be 2. Selectable segments can be statement sequencesstatement sequences or or blocksblocks

3. 3. NNo implicit brancho implicit branch at the end at the end of selectable segmentsof selectable segments ((reliability reliability vs.vs. flexibility flexibility))

4. 4. defaultdefault clause is for clause is for unrepresented values (unrepresented values (it’s it’s optionaloptional))

switch (month) {switch (month) { case 3:case 3: case 4:case 4: case 5: season = "Spring";case 5: season = "Spring";

break;break; case 6:case 6: case 7:case 7: case 8: season = "Summer"; case 8: season = "Summer";

break;break; case 9:case 9: case 10: case 10: case 11: season = "Fall"; case 11: season = "Fall";

break;break; default: season = "Winter";default: season = "Winter";

break;break;}}

* AW Lecture Notes

Page 8: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 8 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Other Multiple SelectorsOther Multiple Selectors

FORTRANFORTRAN Arithmetic IFArithmetic IF

IFIF (arithmetic expression) (arithmetic expression) N1, N2, N3N1, N2, N3 No encapsulatNo encapsulation of ion of selectable segments selectable segments

(they (they could be anywhere)could be anywhere)

Ada's Ada's casecase statementstatement Constant lists can include:Constant lists can include:

SubrangesSubranges e.g., e.g., 10..1510..15 Boolean OR operatorsBoolean OR operators – – e.g., e.g., 1..5 | 7 | 15..201..5 | 7 | 15..20

Lists of constants must be Lists of constants must be exhaustiveexhaustive Often accomplished with Often accomplished with othersothers clause clause This makes it more This makes it more reliablereliable

* AW Lecture Notes

Page 9: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 9 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Iterative StatementsIterative Statements

Iterative StatementIterative Statement: causes a collection of : causes a collection of statements to be executed multiple timesstatements to be executed multiple times

cf.cf. RRecursionecursion: : unit-level controlunit-level control DDesign issuesesign issues::

1. 1. HowHow is iteration controlled? is iteration controlled?

2. 2. WhereWhere is the control mechanism in the loop? is the control mechanism in the loop?

SUM = 0SUM = 0 DODO 20 N = 1, 100, 3 20 N = 1, 100, 3

20 SUM = SUM + N20 SUM = SUM + N

SUM = 0SUM = 0 N = 1N = 1

20 SUM = SUM + N20 SUM = SUM + N N = N + 3;N = N + 3;

IF (N .LE. 100) THENIF (N .LE. 100) THEN GOTOGOTO 20 20

Page 10: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 10 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Counter-Controlled LoopsCounter-Controlled Loops

Design IssuesDesign Issues::1. What are the 1. What are the typetype and and scopescope of the of the loop variableloop variable??

2. What is the 2. What is the valuevalue of the loop variable at of the loop variable at looploop terminationtermination??

3. Should it be legal for the loop variable or 3. Should it be legal for the loop variable or loop parameters loop parameters to be changed in the loop bodyto be changed in the loop body, and if so, does the , and if so, does the change affect loop control?change affect loop control?

4. Should the 4. Should the loop parameters be evaluatedloop parameters be evaluated only once, or only once, or once for every iteration?once for every iteration?

DO 20 N DO 20 N = 1, 100, 3= 1, 100, 320 SUM = SUM + N20 SUM = SUM + N

LLoop oop VVariableariable Initial ValueInitial Value

Terminal ValueTerminal Value

StepsizeStepsize

Lo

op

L

oo

p

Param

etersP

arameters

Page 11: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 11 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

FORTRAN ‘DO’ LoopFORTRAN ‘DO’ Loop

Syntax: Syntax: DODO label var = start, finish [, stepsize] label var = start, finish [, stepsize]

StepsizeStepsize can be any value but zero can be any value but zero ParametersParameters can be expressions can be expressions

Design Design CChoiceshoices::1. 1. Loop variableLoop variable must be must be integerinteger

2. 2. Loop variableLoop variable always has its always has its last valuelast value

3. The 3. The loop variable cannot be changedloop variable cannot be changed in the loop, but in the loop, but the the parameters canparameters can

4. 4. Loop parametersLoop parameters are evaluated only are evaluated only onceonce

* AW Lecture Notes

Page 12: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 12 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

ALGOL 60 ‘For’ LoopALGOL 60 ‘For’ Loop

Syntax: Syntax: forfor var := <list_of_stuff> var := <list_of_stuff> dodo statement statement where <list_of_stuff> can have:where <list_of_stuff> can have: list of expressionslist of expressions expression expression stepstep expression expression untiluntil expression expression expression expression whilewhile boolean_expression boolean_expression

e.g., e.g., for index := 1 step 2 until 50,for index := 1 step 2 until 50, 60, 70, 80,60, 70, 80, index + 1 until 100 doindex + 1 until 100 do

(index = (index = 1, 3, 5, 7, ..., 49,1, 3, 5, 7, ..., 49,60, 70, 80,60, 70, 80, 81, 82, ..., 81, 82, ...,

100)100)

ParametersParameters are evaluated with are evaluated with every iterationevery iteration, , making it very making it very complex and difficult to readcomplex and difficult to read

* AW Lecture Notes

Page 13: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 13 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

‘‘For’ Loops in C-based LanguagesFor’ Loops in C-based Languages

Syntax: Syntax: forfor ([expr_1] ; [expr_2] ; [expr_3]) statement ([expr_1] ; [expr_2] ; [expr_3]) statement The expressions can be The expressions can be statement sequencesstatement sequences, with , with

the statements separated by commas or the statements separated by commas or nullnull

e.g., e.g., for (int i=0, j=10; for (int i=0, j=10; j==ij==i; ; i++, j--i++, j--)) printf(“%d, %d”, i, j);printf(“%d, %d”, i, j);

for (;;) for (;;) …… In In JavaJava, the , the control expressioncontrol expression must be must be BooleanBoolean

Design ChoicesDesign Choices::1, 2. There is 1, 2. There is no explicit loop variableno explicit loop variable

3. 3. Everything can be changedEverything can be changed in the loop in the loop

4. expr_1 is evaluated 4. expr_1 is evaluated onceonce,, others are evaluated with others are evaluated with each iterationeach iteration

Flexible!Flexible!

Page 14: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 14 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Other Counter-Controlled LoopsOther Counter-Controlled Loops

PascalPascalforfor variable := initial ( variable := initial (toto | | downtodownto) final ) final dodo

AdaAdaforfor var var inin [ [reversereverse] ] discrete_rangediscrete_range looploop ......end loopend loop The The loop variable is implicitly declared and loop variable is implicitly declared and

undeclaredundeclared as the loop begins and terminates as the loop begins and terminates

e.g., e.g., CountCount : Float := 1.35; : Float := 1.35; ffor or CountCount in 1..10 loop in 1..10 loop

Sum := Sum + Sum := Sum + CountCount;; end loopend loop

Page 15: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 15 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Logically Controlled LoopsLogically Controlled Loops

Posttest version executes the loop body Posttest version executes the loop body at least at least onceoncee.g., At the above examples, what happens if n is already e.g., At the above examples, what happens if n is already

greater than 100 before reaching to the loop?greater than 100 before reaching to the loop? PascalPascal –– whilewhile …… dodo, , repeatrepeat … … untiluntil AdaAda and and PerlPerl support only pretest versions support only pretest versions FORTRAN 77FORTRAN 77 and and 9090 support neither version support neither version

whilewhile (n <= 100) { (n <= 100) {sum += n;sum += n;n += 3;n += 3;

}}

dodo { {sum += n;sum += n;n += 3;n += 3;

} } whilewhile (n <= 100) (n <= 100)

PretestPretest PosttestPosttest

Page 16: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 16 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

User-Located Loop ControlUser-Located Loop Control

Design IssuesDesign Issues::

1. Should the 1. Should the conditionalconditional be part of be part of the exit?the exit?C-basedC-based –– unconditional unconditionalAdaAda –– conditional ( conditional (exit when exit when ……))

2. Can control be transferable out 2. Can control be transferable out of more than one loop?of more than one loop?JavaJava, , C#C#, , PerlPerl –– YesYes

whilewhile (n <= 100) { (n <= 100) {sum += n;sum += n;if (sum == m) if (sum == m) continuecontinue;;n += 3;n += 3;

}}

whilewhile (n <= 100) { (n <= 100) {sum += n;sum += n;if (sum == m) if (sum == m) breakbreak;;n += 3;n += 3;

}}

outout::forfor (int i=0; i<k; i++) { (int i=0; i<k; i++) {

whilewhile (n <= 100) { (n <= 100) { sum += n;sum += n; if (sum == m)if (sum == m) break break outout;; n += 3;n += 3;

}}}} JavaJava

Page 17: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 17 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Iteration Based on Data Structures &Iteration Based on Data Structures &Unconditional BranchingUnconditional Branching

IBDS: Use order and number of IBDS: Use order and number of elements of elements of some data structuressome data structures to control iteration to control iteration

Unconditional Branching (Goto)Unconditional Branching (Goto) Problem: Problem: readabilityreadability –– Spaghetti LogicSpaghetti Logic Some languages do not have them: e.g., Java, Some languages do not have them: e.g., Java,

Modular-2Modular-2 Loop exit statementsLoop exit statements are restricted and somewhat are restricted and somewhat

camouflaged goto’scamouflaged goto’s

String[] String[] wdayswdays = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri” }; = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri” };……foreachforeach (String name (String name inin wdayswdays))

Console.WriteLine(“Work Day: {0}”, name);Console.WriteLine(“Work Day: {0}”, name); C#C#

Page 18: April 16, 2004 1 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)

April 16, 2004 18 ICE 1341 – Programming Languages (Lecture #14) In-Young Ko

Guarded CommandsGuarded Commands (Dijstra, 1975) (Dijstra, 1975)

If more than one are true, If more than one are true, choose one choose one nondeterministicallynondeterministically

Runtime errorRuntime error when non of the when non of the conditions is trueconditions is true

ifif i = 0 -> sum := sum + i i = 0 -> sum := sum + i[][] i > j -> sum := sum + j i > j -> sum := sum + j[][] j > I -> sum := sum + I j > I -> sum := sum + Ififi

Allow Allow verificationverification during program development during program development

dodo q1 > q2 -> temp := q1; q1 := q2; q2 := temp; q1 > q2 -> temp := q1; q1 := q2; q2 := temp;[][] q2 > q3 -> temp := q2; q2 := q3; q3 := temp; q2 > q3 -> temp := q2; q2 := q3; q3 := temp;[][] q3 > q4 -> temp := q3; q3 := q4; q4 := temp; q3 > q4 -> temp := q3; q3 := q4; q4 := temp;odod If more than one are true, choose one nondeterministically; If more than one are true, choose one nondeterministically;

then then start loop againstart loop again If none are true, If none are true, exit loopexit loop