ice1341 programming languages spring 2005 lecture #13 lecture #13 in-young ko iko.at. icu.ac.kr...
TRANSCRIPT
ICE1341 ICE1341 Programming LanguagesProgramming Languages
Spring 2005Spring 2005
Lecture #13Lecture #13
In-Young Koiko .AT. icu.ac.kr
Information and Communications University (ICU)
Spring 2005 2 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Chapter 7 – Expressions and Assignment Chapter 7 – Expressions and Assignment StatementsStatements Side EffectsSide Effects Overloaded OperatorsOverloaded Operators Type ConversionsType Conversions Short-circuit ExpressionsShort-circuit Expressions Mixed-mode AssigmentsMixed-mode Assigments
Java allows widening type coercionsJava allows widening type coercions
Last LectureLast Lecture
Spring 2005 3 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
This LectureThis Lecture
Chapter 8 – Statement-Level Control Chapter 8 – Statement-Level Control StructuresStructures Selection StatementsSelection Statements Iterative StatementsIterative Statements Unconditional BranchingUnconditional Branching Guarded CommandsGuarded Commands
Spring 2005 4 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Chapter 8Chapter 8Statement-Level Control Statement-Level Control
StructuresStructures
Spring 2005 5 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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
Spring 2005 6 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Nested Two-Way SelectorsNested Two-Way Selectors
ALGOL 60ALGOL 60 – disallow – disallow direct nestingdirect nesting
if ... thenif ... then beginbegin if ...then ...if ...then ... endend else ...else ...
JavaJava – – elseelse goes with goes with the the nearestnearest ififif ... if ...
ifif ... ... elseelse ... ...
FORTRAN 90 FORTRAN 90 and and AdaAda – closing special words– closing special words
ifif ... then ... then ifif ... then ... ... then ... end ifend if else ...else ... end ifend if
Spring 2005 7 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Testing Nested IfsTesting Nested Ifspublic class TestNestedIfs {public class TestNestedIfs { public static void main(String args[]) {public static void main(String args[]) {
int n = 3;int n = 3;ifif (n < 5) (n < 5)
ifif (n > 3) (n > 3)System.out.println("n is greater than 3.");System.out.println("n is greater than 3.");
elseelse System.out.println("n is not greater than 3.");System.out.println("n is not greater than 3.");
}}}}
d:\ICE1341\Samples>java TestNestedIfsd:\ICE1341\Samples>java TestNestedIfsN is not greater than 3.N is not greater than 3.
Spring 2005 8 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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
Spring 2005 9 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Multiple Selection Statements (2)Multiple Selection Statements (2)
Design Choices (C Switch)Design Choices (C Switch)::1. Control expression can be 1. Control expression 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. No implicit branchNo implicit branch at the end at the end of selectable segments of selectable segments ((reliability vs. flexibilityreliability vs. flexibility))
4. 4. defaultdefault clause is for clause is for unrepresented values (it’s unrepresented values (it’s optional)optional)
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
Spring 2005 10
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Other Multiple SelectorsOther Multiple Selectors
FORTRANFORTRAN Arithmetic IFArithmetic IF
IFIF (arithmetic expression) (arithmetic expression) N1, N2, N3N1, N2, N3 No encapsulation of selectable segments No encapsulation of selectable segments
(they could be anywhere)(they could be anywhere)
Ada's case statementAda's case statement 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
Spring 2005 11
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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. RecursionRecursion: : unit-level controlunit-level control Design issuesDesign 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
Spring 2005 12
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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 loop terminationloop termination??
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
Loop VariableLoop Variable Initial ValueInitial Value
Terminal ValueTerminal Value
StepsizeStepsize
Lo
op
L
oo
p
Param
etersP
arameters
Spring 2005 13
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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 ChoicesDesign Choices::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
Spring 2005 14
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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 list of expressionexpressionss expressionexpression stepstep expressionexpression untiluntil expressionexpression expressionexpression whilewhile boolean_expressionboolean_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, 81, 82, 83, ..., 100)60, 70, 80, 81, 82, 83, ..., 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
Spring 2005 15
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
‘‘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!
Spring 2005 16
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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; for for CountCount in 1..10 loop in 1..10 loop
Sum := Sum + Sum := Sum + CountCount;; end loopend loop
Count is an integer Count is an integer loop variableloop variable
Count is a float variableCount is a float variable
Spring 2005 17
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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 support only pretest versionsonly pretest versions FORTRAN 77FORTRAN 77 and and 9090 support support neither versionneither 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
Spring 2005 18
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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 of more than one loopmore 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
Spring 2005 19
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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#
Spring 2005 20
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
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 Can be used to represent Can be used to represent concurrencyconcurrency
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