ICE1341 Programming Languages Spring 2005 Lecture #12 Lecture #12 In-Young Ko iko.AT. icu.ac.kr...
-
Upload
phoebe-murray -
Category
Documents
-
view
215 -
download
0
Transcript of ICE1341 Programming Languages Spring 2005 Lecture #12 Lecture #12 In-Young Ko iko.AT. icu.ac.kr...
ICE1341 ICE1341 Programming LanguagesProgramming Languages
Spring 2005Spring 2005
Lecture #12Lecture #12
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
Postmortem of MidtermPostmortem of Midterm
Why the Von Neumann machine is Why the Von Neumann machine is important in designing programming important in designing programming languages?languages?
Spring 2005 3 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Postmortem of Midterm Postmortem of Midterm
The set of all strings with an equal number The set of all strings with an equal number of 0’s and 1’sof 0’s and 1’s
Can’t generate by using a regular Can’t generate by using a regular grammar!grammar!
The set of all strings with an equal number The set of all strings with an equal number of 0’s and 1’s, of 0’s and 1’s, such that no prefix has two such that no prefix has two more 0’s than 1’s, nor two more 1’s than 0’smore 0’s than 1’s, nor two more 1’s than 0’s
(01|10)*(01|10)*
Spring 2005 4 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Postmortem of MidtermPostmortem of Midterm<computers><computers>
<computer><computer><model><model>sm1234sm1234</model></model><manufacturer><manufacturer>SamsungSamsung</manufacturer></manufacturer><price unit=<price unit=””WonWon””>>1,500,0001,500,000</price></price><motherboard><motherboard> <cpu><cpu>
<manufacturer><manufacturer>IntelIntel</manufacturer></manufacturer><model><model>Pentium 4Pentium 4</model></model><speed unit=<speed unit=””GHzGHz””>>2.42.4</speed></speed>
</cpu></cpu> <memory><memory>
<manufacturer><manufacturer>SamsungSamsung</</manufacturer>manufacturer>
<type><type>DDR SDRAMDDR SDRAM</type></type><size unit=<size unit=””GBGB””>>1.01.0</size></size>
</memory></memory></motherboard></motherboard>
</computer></computer><computer><computer>
......</computer></computer>
......</computers></computers>
Spring 2005 5 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Postmortem of MidtermPostmortem of Midterm<computers><computers>
<computer><computer><model><model>sm1234sm1234</model></model><manufacturer><manufacturer>SamsungSamsung</manufacturer></manufacturer><price unit=<price unit=””WonWon””>>1,500,0001,500,000</price></price><motherboard><motherboard> <cpu><cpu>
<manufacturer><manufacturer>IntelIntel</manufacturer></manufacturer><model><model>Pentium 4Pentium 4</model></model><speed unit=<speed unit=””GHzGHz””>>2.42.4</speed></speed>
</cpu></cpu> <memory><memory>
<manufacturer><manufacturer>SamsungSamsung</</manufacturer>manufacturer>
<type><type>DDR SDRAMDDR SDRAM</type></type><size unit=<size unit=””GBGB””>>1.01.0</size></size>
</memory></memory></motherboard></motherboard>
</computer></computer><computer><computer>
......</computer></computer>
......</computers></computers>
computerscomputers ‘ ‘<computers><computers>’ ’ { { computercomputer } ‘ } ‘</computers></computers>’’
computercomputer ‘ ‘<computer><computer>’ ’ modelmodel manufacturermanufacturer priceprice motherboardmotherboard ‘‘</computer></computer>’’
modelmodel ‘ ‘<model><model>’ ’ stringstring ‘ ‘</model></model>’’
manufacturermanufacturer ‘ ‘<manufacturer><manufacturer>’ ’ stringstring ‘ ‘</manufacturer></manufacturer>’’
priceprice ‘ ‘<price<price ’ [‘ ’ [‘unit=“unit=“’ ’ stringstring ‘ ‘”” ’] ‘ ’] ‘>>’ ’ numnum ‘ ‘</price></price>’’
motherboardmotherboard ‘ ‘<motherboard><motherboard>’ ’ cpucpu memorymemory ‘ ‘</motherboard></motherboard>’’
……
Spring 2005 6 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
AnnouncementsAnnouncements Midterm ProjectMidterm Project
Due: Due: Thursday April 14Thursday April 14thth
The content of the project report and presentationThe content of the project report and presentation Main design goals and application domainsMain design goals and application domains of the of the
programming language designedprogramming language designed The The language designlanguage design described in EBNF described in EBNF A A sample programsample program (displayed in MS IE) (displayed in MS IE) DiscussionsDiscussions about the language design factors & about the language design factors &
lessons learnedlessons learned 10 minute10 minute presentation presentation per each team per each team Send me Send me your presentation fileyour presentation file by by 10:00AM10:00AM
Spring 2005 7 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Data TypesData Types More on ArraysMore on Arrays RecordsRecords UnionsUnions PointersPointers
Last LectureLast Lecture
Spring 2005 8 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
This LectureThis Lecture
Chapter 7 – Expressions and Assignment Chapter 7 – Expressions and Assignment StatementsStatements
Chapter 8 – Statement-Level Control Chapter 8 – Statement-Level Control StructuresStructures
Spring 2005 9 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Pointer TypesPointer Types
int n = 11;int n = 11;
int *p = 22;int *p = 22;
int *q, *r, *h;int *q, *r, *h;
q = &n; r = NULL;q = &n; r = NULL;
h = (int *)malloc(sizeof(int));h = (int *)malloc(sizeof(int));
*h = 33;*h = 33;
int m = *h;int m = *h;
11nn22
pp
NULL
qqrr
…
33
hh
Spring 2005 10
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Pointer TypesPointer Types
int n = 11;int n = 11;
int *p = (int *)malloc(sizeof(int));int *p = (int *)malloc(sizeof(int));
*p = 22;*p = 22;
int *q, *r, *h;int *q, *r, *h;
q = &n; r = NULL;q = &n; r = NULL;
h = (int *)malloc(sizeof(int));h = (int *)malloc(sizeof(int));
*h = 33;*h = 33;
int m = *h;int m = *h;
11nn22
pp
NULL
qqrr
…
33
hh
Spring 2005 11
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Chapter 7Chapter 7Expressions and Expressions and
Assignment StatementsAssignment Statements
Spring 2005 12
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Arithmetic ExpressionsArithmetic Expressions
Arithmetic expressions consist of Arithmetic expressions consist of operatorsoperators, , operandsoperands, , parenthesesparentheses, and , and function callsfunction calls
Unary OperatorsUnary Operators
e.g., e.g., !!,, ++ ++,, -- --,, + (identity operator) + (identity operator),, - - Binary OperatorsBinary Operators
e.g., e.g., &&&&,, || ||,, == ==,, != !=,, + +,, - -,, * *,, / / Ternary OperatorsTernary Operators
e.g., expr1 e.g., expr1 ?? expr2 expr2 :: expr3 expr3
a + b * Math.sqrt(c) + (f (obj) - 1.257 + obj.d)a + b * Math.sqrt(c) + (f (obj) - 1.257 + obj.d)
Spring 2005 13
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Design Issues for Arithmetic Design Issues for Arithmetic ExpressionsExpressions
What are the What are the operator precedence rulesoperator precedence rules?? What are the What are the operator associativity rulesoperator associativity rules?? What is the What is the order of operand evaluationorder of operand evaluation?? Are there restrictions on operand evaluation Are there restrictions on operand evaluation
side effectsside effects?? Does the language allow user-defined Does the language allow user-defined operator operator
overloadingoverloading?? What What type mixingtype mixing is allowed in expressions? is allowed in expressions?
* AW Lecture Notes
a + b * Math.sqrt(c) + (f (obj) - 1.257 + obj.d)a + b * Math.sqrt(c) + (f (obj) - 1.257 + obj.d)
Spring 2005 14
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Operator Precedence RulesOperator Precedence Rules
Define the Define the orderorder in which adjacent operators in which adjacent operators of of differentdifferent precedence levels are precedence levels are evaluatedevaluated
Typical precedence levels: Typical precedence levels: ParenthesesParentheses Unary operatorsUnary operators **** *, /*, / +, -+, -
a + b * c + ++d – (e + f)a + b * c + ++d – (e + f)(1)(1)(2)(2)(3)(3)
(4)(4)
(5)(5)
(6)(6)
* AW Lecture Notes
Spring 2005 15
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Operator Associativity RulesOperator Associativity Rules
Define the order in which adjacent operators Define the order in which adjacent operators with the with the samesame precedence level are evaluated precedence level are evaluated
Typical associativity rules: Typical associativity rules: Left to rightLeft to right (except (except **** in Ada and Fortran) in Ada and Fortran)
APLAPL; all operators have equal precedence and ; all operators have equal precedence and all operators associate all operators associate right to leftright to left
Precedence and associativity rules can be Precedence and associativity rules can be overriden with overriden with parenthesesparentheses (e.g., to improve (e.g., to improve precision in calculating large numbers)precision in calculating large numbers)
* AW Lecture Notes
a + b - c; a ** b ** c; - a - b; - a ** b;a + b - c; a ** b ** c; - a - b; - a ** b;
- 17 mod 5- 17 mod 5
Spring 2005 16
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Operand Evaluation OrderOperand Evaluation Order
VariablesVariables: just fetch the value from memory: just fetch the value from memory ConstantsConstants: sometimes a fetch from memory; : sometimes a fetch from memory;
sometimes the constant is in the machine sometimes the constant is in the machine language instructionlanguage instruction
Parenthesized expressionsParenthesized expressions: evaluate all : evaluate all operands and operators firstoperands and operators first
Function referencesFunction references: need to consider : need to consider side side effectseffects
* AW Lecture Notes
a + b * Math.sqrt(c) + (f (obj) - 1.257 + obj.d)a + b * Math.sqrt(c) + (f (obj) - 1.257 + obj.d)
Spring 2005 17
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Side EffectsSide Effects
Functional side effectsFunctional side effects occur when a function occur when a function changes a changes a two-way parametertwo-way parameter or a or a nonlocal variablenonlocal variable
Possible Solutions:Possible Solutions: Allow no Allow no two-way parameterstwo-way parameters and and non-local referencesnon-local references in in
functions (functions ( impossible to return multiple values from a impossible to return multiple values from a function, inefficiency in parameter passing)function, inefficiency in parameter passing)
Fix the operand evaluation order (Fix the operand evaluation order ( limits compiler limits compiler optimizations) optimizations)
int main() {int main() {int a = 10;int a = 10;int b = int b = a + triple(&a)a + triple(&a);;
}}
int triple(int *val) {int triple(int *val) {(*val) *= 3;(*val) *= 3;return *val;return *val;
}}
* AW Lecture Notes
Spring 2005 18
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Overloaded OperatorsOverloaded Operators
Operator OverloadingOperator Overloading: use of an operator for : use of an operator for more than one purposemore than one purpose
Need to consider Need to consider readabilityreadability and and reliabilityreliability of an of an overloaded operatoroverloaded operator
C++ and Ada allow C++ and Ada allow user-defined overloaded user-defined overloaded operatorsoperators
e.g., e.g., int a[10], b[];int a[10], b[];
b = a + 5; b = a + 5; //??? //???
int a, *b, c; float d;int a, *b, c; float d;
r = a r = a ** **b b ++ c – (d c – (d ++ 1.345) 1.345)
r = 3 r = 3 // 5 5
r := 3 r := 3 divdiv 5 5
Spring 2005 19
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Type ConversionsType Conversions Narrowing ConversionNarrowing Conversion: converts an object to a type that : converts an object to a type that
cannot include all of the values of the original type cannot include all of the values of the original type e.g., e.g., floatfloat intint
Widening ConversionWidening Conversion : converts an object to a type that : converts an object to a type that can include at least can include at least approximationsapproximations to all of the values of to all of the values of the original type the original type e.g., e.g., intint floatfloat
Mixed-mode ExpressionMixed-mode Expression: has operands of different types: has operands of different types CoercionCoercion: an : an implicitimplicit type conversion type conversion
e.g., e.g., int num = 3.14;int num = 3.14; Ada provides virtually no coercions in expressionsAda provides virtually no coercions in expressions
Type CastingType Casting: an : an explicitexplicit type conversion type conversione.g., e.g., int num = int num = (int)(int)3.14;3.14;
FloatFloat(sum)(sum) -- as a function call-- as a function call* AW Lecture Notes
Spring 2005 20
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Relational and Boolean ExpressionsRelational and Boolean Expressions
Relational OperatorRelational Operator: an operator that : an operator that compares the values of two operands and compares the values of two operands and returns a Boolean valuereturns a Boolean value e.g., e.g., !=!=, , /=/=, , .NE..NE., , <><>
Boolean OperatorBoolean Operator: an operator which : an operator which operands are Boolean and its result is Booleanoperands are Boolean and its result is Boolean e.g., e.g., .AND..AND., , .OR..OR., , .NOT..NOT., , &&&&, , ||||, , !! C has no Boolean type – it uses C has no Boolean type – it uses intint type with 0 for type with 0 for
false and nonzero for truefalse and nonzero for true
e.g., e.g., a > b > ca > b > c // ??? // ??? * AW Lecture Notes
!!(a (a !=!= b b &&&& c c >> d d |||| e) e)
Spring 2005 21
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Short-Circuit EvaluationShort-Circuit Evaluation
Short-Circuit ExpressionShort-Circuit Expression: an expression : an expression which result is determined without evaluating all which result is determined without evaluating all of the operands and operatorsof the operands and operators
A short-circuit expression may prevent A short-circuit expression may prevent side side effectseffects in the expression in the expression
e.g., e.g., (a > b || ((b++) / 3)(a > b || ((b++) / 3) Ada allows the programmers to specify short-Ada allows the programmers to specify short-
circuit evaluation (circuit evaluation (and thenand then, , or elseor else))
(13 * a) * (b / 13 – 1)(13 * a) * (b / 13 – 1)
(a >= 0) && (b < 10)(a >= 0) && (b < 10)
if (i < len && a[i] != 0)if (i < len && a[i] != 0)
a[i] *= 2;a[i] *= 2;
Spring 2005 22
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Assignment StatementsAssignment Statements
Simple AssignmentSimple Assignment (e.g., (e.g., a = 10a = 10,, PascalPascal A := 10A := 10)) Multiple TargetsMultiple Targets (e.g., (e.g., PL/IPL/I A, B = 10A, B = 10)) Conditional TargetsConditional Targets
(e.g., (e.g., C-basedC-based (first==true)? total : subtotal = 0(first==true)? total : subtotal = 0)) Compound Assignment OperatorsCompound Assignment Operators
(e.g., (e.g., C-based C-based sum += next;sum += next;)) Unary Assignment OperatorsUnary Assignment Operators (e.g., (e.g., C-basedC-based a++;a++;)) Assignment as an ExpressionAssignment as an Expression
(e.g., (e.g., CC while ((while ((ch=getchar()ch=getchar()) != EOF) { … }) != EOF) { … }
sum = count = 0; sum = count = 0; // multiple targets)// multiple targets)
Spring 2005 23
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Mixed-mode AssignmentMixed-mode Assignment
In FORTRAN, C, and C++, In FORTRAN, C, and C++, any numeric value any numeric value can be assigned to any numeric scalar variablecan be assigned to any numeric scalar variable
e.g., e.g., float val = 12; int num = 12.35;float val = 12; int num = 12.35; In Java and C#, only In Java and C#, only widening assignment widening assignment
coercionscoercions are allowed are allowed
e.g., e.g., float val = 12; int num = float val = 12; int num = (int)12.35;(int)12.35;
In Ada, there is In Ada, there is no assignment coercionno assignment coercion
Spring 2005 24
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Chapter 8Chapter 8Statement-Level Control Statement-Level Control
StructuresStructures
Spring 2005 25
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 26
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Selection StatementsSelection Statements
Selection StatementSelection Statement: a means of : a means of choosing between choosing between two or more execution pathstwo or more execution paths in a program in a program
Two general categories: Two 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
Spring 2005 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
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 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, 81, 82, ..., 100)60, 70, 80, 81, 82, ..., 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 35
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 36
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
Spring 2005 37
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 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
Spring 2005 38
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 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
Spring 2005 39
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 40
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
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