ice1341 programming languages spring 2005 lecture #14 lecture #14 in-young ko iko.at. icu.ac.kr...
TRANSCRIPT
ICE1341 ICE1341 Programming LanguagesProgramming Languages
Spring 2005Spring 2005
Lecture #14Lecture #14
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 8 – Statement-Level Control Chapter 8 – Statement-Level Control StructuresStructures Selection StatementsSelection Statements Iterative StatementsIterative Statements
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 Unconditional BranchingUnconditional Branching Guarded CommandsGuarded Commands
FORTRAN ProgrammingFORTRAN Programming
Spring 2005 4 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 5 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 6 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 7 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 8 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 9 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 10
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 11
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 12
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
Spring 2005 13
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
FORTRAN FORTRAN ((ForFormula mula TranTranslating System)slating System)
Designed to efficiently translate mathematical Designed to efficiently translate mathematical formulas into formulas into IBM 704IBM 704 machine code machine code
IBM 704IBM 704 (1954) (1954)““The first mass-produced The first mass-produced
computer with computer with core core memorymemory and and floating-floating-
point arithmeticpoint arithmetic”” Photo: Lawrence Livermore National Laboratory
Spring 2005 14
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
FORTRAN Coding FormatFORTRAN Coding Format
FORTRAN programs FORTRAN programs were written in a were written in a coding form with a coding form with a strict formatting rulestrict formatting rule
Continuation (6) Continuation (6)
FORTRAN Statement (7-72)FORTRAN Statement (7-72)
Identification Sequence (73-80)Identification Sequence (73-80)
Statement Number (1-5)Statement Number (1-5)
J.W. Perry Cole, ANSI FORTRAN IV,
wcb
Spring 2005 15
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Punched CardsPunched Cards
Coded FORTRAN programs Coded FORTRAN programs were converted onto were converted onto
punched cards for loading punched cards for loading
Photos: http://www.tno.nl/instit/fel/museum/computer/en/punchcards.html
Spring 2005 16
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Early FORTRAN VersionsEarly FORTRAN Versions
FORTRAN I (1957)FORTRAN I (1957) NamesNames could have up to could have up to six characterssix characters (IBM 704 has (IBM 704 has
a 6-bit BCD character set and 36-bit word)a 6-bit BCD character set and 36-bit word) Post-test counting loopPost-test counting loop ( (DODO), ), Formatted I/OFormatted I/O, , User-User-
defined subprogramsdefined subprograms, , Three-way selection Three-way selection statementstatement (arithmetic (arithmetic IFIF))
No data typing statements (No data typing statements (Implicit Type DeclarationImplicit Type Declaration – Variables whose names begin with I, J, K, L, M, – Variables whose names begin with I, J, K, L, M, and N are integer types, all others are floating point)and N are integer types, all others are floating point)
FORTRAN II (1958)FORTRAN II (1958) Independent compilationIndependent compilation of subroutines of subroutines
* AW Lecture Notes
Spring 2005 17
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Later FORTRAN VersionsLater FORTRAN Versions
FORTRAN IV (1960-62) – ANSI standard in 1966FORTRAN IV (1960-62) – ANSI standard in 1966 Explicit type declarationsExplicit type declarations Logical selection statementLogical selection statement Subprogram names could be parametersSubprogram names could be parameters
FORTRAN 77 (1978)FORTRAN 77 (1978) Character stringCharacter string handling handling Logical loop control statementLogical loop control statement IF-THEN-ELSEIF-THEN-ELSE statement statement
FORTRAN 90 (1990)FORTRAN 90 (1990) Free coding formatFree coding format Modules, Dynamic arrays, Pointers, Recursion, Modules, Dynamic arrays, Pointers, Recursion, CASECASE
statementstatement* AW Lecture Notes
Spring 2005 18
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
A Sample FORTRAN ProgramA Sample FORTRAN Program
C *** This is a sample FORTRAN IV programC *** This is a sample FORTRAN IV program
PROGRAM SAMPLEPROGRAM SAMPLE
READ (5, 990) A, BREAD (5, 990) A, B
990990 FORMAT (F5.2, F5.2)FORMAT (F5.2, F5.2)
SUM = A + BSUM = A + B
WRITE (6, 81) A, B, SUMWRITE (6, 81) A, B, SUM
8181 FORMAT (1X, F5.2, 3X, F5.2, 3X, F6.2)FORMAT (1X, F5.2, 3X, F5.2, 3X, F6.2)
STOPSTOP
ENDEND
J.W. Perry Cole, ANSI FORTRAN IV, wcb
Spring 2005 19
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
FORTRAN Data Types (1)FORTRAN Data Types (1)
IntegerInteger Implicit TypingImplicit Typing: Variables whose names begin with I~N: Variables whose names begin with I~N Explicit DeclarationExplicit Declaration
e.g., e.g., INTEGER A, TOTALINTEGER A, TOTAL Real Real – Single precision floating point number– Single precision floating point number
Implicit TypingImplicit Typing: Variables whose names begin with : Variables whose names begin with other than A~H or O-Zother than A~H or O-Z
Explicit DeclarationExplicit Declaration
e.g., e.g., REAL J, RREAL J, R Double precisionDouble precision floating point number floating point number
e.g., e.g., DOUBLE PRECISION A, XDOUBLE PRECISION A, X
Spring 2005 20
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
FORTRAN Data Types (2)FORTRAN Data Types (2)
Complex Complex e.g., e.g., COMPLEX A, B, CCOMPLEX A, B, C
A = (3.5, -7.24)A = (3.5, -7.24) B = (-8.21, 5.67)B = (-8.21, 5.67) C = A + BC = A + B
CharacterCharactere.g., e.g., CHARACTER C, NAME*20, ADDR*30CHARACTER C, NAME*20, ADDR*30 CHARACTER*20 STR1, STR2CHARACTER*20 STR1, STR2
Character constants: e.g., Character constants: e.g., ‘C’‘C’,, ‘Go ICU’ ‘Go ICU’ Hollerith StringsHollerith Strings:: e.g., 1HC, 5HGoICU e.g., 1HC, 5HGoICU
LogicalLogical (Boolean) (Boolean)e.g., e.g., LOGICAL X, Y, FLAGLOGICAL X, Y, FLAG
Logical constants: Logical constants: .TRUE..TRUE. or or .FALSE..FALSE.
Spring 2005 21
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Variable Initializations and ArraysVariable Initializations and Arrays
Variable InitializationsVariable Initializations
e.g., e.g., DATA A/1.0/, L/2/, B,C/4.0, 5.0/DATA A/1.0/, L/2/, B,C/4.0, 5.0/
DATA ARYX(3)/1.333/, DATA ARYX(3)/1.333/, T(1),T(2),T(3)/3*0.0/T(1),T(2),T(3)/3*0.0/
DATA C(1)/1HS/, C(2)/1HD/, TAG/3HYesDATA C(1)/1HS/, C(2)/1HD/, TAG/3HYes ArraysArrays
e.g., e.g., DIMENSION A(5), B(10,7), N(3,5,20)DIMENSION A(5), B(10,7), N(3,5,20)
INTEGER X(7,5)INTEGER X(7,5)
REAL MATRIX(-6:4, 7, -5:10), KREAL MATRIX(-6:4, 7, -5:10), K
DIMENSION K(20)DIMENSION K(20)J.W. Perry Cole, ANSI FORTRAN IV, wcb
Spring 2005 22
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
FORTRAN OperatorsFORTRAN Operators
Arithmetic Operators: Arithmetic Operators: ++, , --, , **, , //, , **** (exponentiation) (exponentiation) Mixed mode expressions – evaluated in integer mode Mixed mode expressions – evaluated in integer mode if all if all
operands are integeroperands are integer, evaluated in real mode otherwise, evaluated in real mode otherwisee.g., e.g., 86.3 * K + R / 16.5 ** J86.3 * K + R / 16.5 ** J All are evaluated in All are evaluated in
realreal
Relational Operators: Relational Operators: .LT..LT.,,.LE.LE.,.,.GT..GT.,,.GE..GE.,,.EQ..EQ.,,.NE..NE.e.g., e.g., IF (RESULT .LT. 0.0) STOPIF (RESULT .LT. 0.0) STOP
Logical Operators: Logical Operators: .AND..AND., , .OR..OR., , .NOT..NOT.e.g., e.g., IF (N .EQ. 1 .OR. .NOT. R .LT. 0.0) GOTO 75IF (N .EQ. 1 .OR. .NOT. R .LT. 0.0) GOTO 75
Multiple Assignment StatementsMultiple Assignment Statementse.g., e.g., A = I = V = W = .2 * R + XA = I = V = W = .2 * R + X A truncated value will be assigned to A and IA truncated value will be assigned to A and I
Spring 2005 23
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Program Flow ControlProgram Flow Control
GotoGoto GOTO (10, 20, 30) KCOUNTGOTO (10, 20, 30) KCOUNT
Logical IFLogical IF IF (K .LT. 1) K = K + 1IF (K .LT. 1) K = K + 1
Arithmetic IFArithmetic IF IF (A / T – S) 10, 20, 30IF (A / T – S) 10, 20, 30
Block IFBlock IF IF (M .GT. 15) THEN M = M / 3IF (M .GT. 15) THEN M = M / 3ELSE M = M * 3ELSE M = M * 3ENDIFENDIF
Do loopsDo loops DO 10 I = 1, N, 2DO 10 I = 1, N, 2 SUM = SUM + ISUM = SUM + I
10 CONTINUE10 CONTINUE