25
1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion Iteration is statement level Recursion is unit-level control next chapter Design issues 1. How is iteration controlled ? boolean expression or counter? 2. Where is the control mechanism ? pre or post?

1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

Embed Size (px)

Citation preview

Page 1: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

1Iterative Statements

• Repeated execution of a (compound) statement by iteration or recursion– Iteration is statement level

– Recursion is unit-level control • next chapter

• Design issues1. How is iteration controlled ?

• boolean expression or counter?

2. Where is the control mechanism ?• pre or post?

Page 2: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

2Counter-Controlled Loops

• Counting loop variable– the variable– a means of specifying the initial and terminal values– step-size values

• Design Issues1. What are the type and scope of the loop variable?

2. What is the value of the loop variable at loop termination?

3. Is it legal to change the loop variable or loop parameters in the loop body?

• if so, does the change affect loop control?

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

Page 3: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

3Iterative Statements: FORTRAN's DO

• FORTRAN 90 syntaxDO label var = initial, final [, stepsize]

• Stepsize can be any value but zero• Parameters can be expressions• Design choices:

1. Loop variable must be INTEGER

2. Loop variable has its last value after loop termination

3. Loop variable cannot be changed in the loop

4. Loop parameters are evaluated only once

5. Parameters can be changed in the loop• Changing them does not affect loop control

• FORTRAN 95: a second form[name:] DO variable = initial, final [,stepsize]

END DO [name]

– Loop variable must be an INTEGER

Page 4: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

4Iterative Statements: Pascal's for

• Pascal’s for statementfor variable := initial (to|downto) final do statement

• Design choices:1. Loop variable must be an ordinal type of usual scope

2. After normal termination, loop variable is undefined

3. The loop variable cannot be changed in the loop;

4. Loop parameters can be changed

5. Loop parameters are evaluated just once1. Changing them does not affect loop control

• Endless loops are avoided

Page 5: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

5Iterative Statements: Ada

• Adafor var in [reverse] discrete_range loop

...

end loop

• A discrete_range is a sub-range of an integer or enumeration type

• Scope of the loop variable is the loop body• Loop variable is implicitly undeclared after loop

termination

Page 6: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

6Iterative Statements: C's for

• C’s for statementfor ([expr_1] ; [expr_2] ; [expr_3]) statement

• The expressions can be – Whole statements, or even

– Statement sequences• The statements separated by commas• The value is the value of the last statement

• There is no explicit loop variable• Everything can be changed in the loop• The first expression is evaluated once• The other two expressions are evaluated with each iteration• The 2nd expression is evaluated before each iteration• The 3rd expression is evaluated before each iteration

Page 7: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

7Iterative Statements: C++ and Java

• C++ differs from C in that1. The control expression can also be Boolean

2. The initial expression can include variable definitions• The scope is the definition and the loop body

• Java and C# differ from C++ in that– The control expression must be Boolean– Less error-prone

• but not completely, e.g.– for (; b1 = b2;) {…} // b1, b2 boolean; b2 is true?!

Page 8: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

8Logically-Controlled Loops

• Repetition control is based on a Boolean expression• Design issues:

– Pre-test or post-test?– Is the logically controlled loop a special case of counting loop?– Expression rather than a counter

• General forms:

1. while (ctrl_expr) loop_body

2. do loop_body while (ctrl_expr)

Page 9: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

9Logically-Controlled Loops in PLs

• Pascal– Separate pre-test and post-test logical loops

• while … do …• repeat … until …

– while tests for true, until tests for false

• C and C++– Separate pre-test and post-test logical loops

• while (…) …• do … while (…)

– Both control expression test for true

• Java is like C, but– Control expressions must be Boolean

Page 10: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

10Logically-Controlled Loops in PLs (cont.)

• Ada– only pre-test logical loop

• FORTRAN 77 and 90 – no logical loops

• Perl – two pre-test logical loops, while and until– no post-test logical loop

Page 11: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

11User-Located Loop Control

• Convenience for control to skip part of loop body

• Simple design for single loops– e.g., break

• Design issues for nested loops1. Is the condition executed before exiting?

2.Can control exit more than the innermost loop?

Page 12: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

12User-Located Loop Control: break, continue

• C , C++, and Java– break statement exits the loop

• Unconditional• One level only• Can be used in any loop type• Also used in switch

– continue statement skips the remainder of the iteration, but does not exit the loop

• Java and C# – A labeled break statement transfers control to the label

• Also, a return statement exits loops– it exits a subprogram (see later)

Page 13: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

13Lisp – General Iteration with do

• The do macro is CL’s fundamental iteration operator(do ((var-1 value-1 next-1)* ... )

(<exit-test> <forms-at-exit>* <result>)

<body-forms>)

• First argument is – a list of variable specifications

– form: (var initial-value update)

• The second argument is– a list containing one or more expressions (<expr-1> <expr>*)– The 1st expression expr-1 is the termination test

– The remaining expressions are evaluated in order when the test is false

– The value of the last expression is the result value of the loop

– The remaining arguments are the loop body

Page 14: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

14Iteration Based on Data Structures

• Concept– Use order and number of elements in a data structure

to control iteration

• Control mechanism– Calls a function that returns the next element in the order– Exit loop if there is no such element

• In C, for can be used to build a user-defined iterator– e.g., for (p = head; p; p = next(p)) {...}

Page 15: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

15Lisp Specialized Iteration

1. Iterate over integers from 0 to limit:(dotimes (<var> <limit>

<return-value>)

<forms>*)

2. Iterate over elements of a list:(dolist (<var> <list>

<return-value>)

<forms>*)

Page 16: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

16Iteration on Data Structures (cont.)

• C#– 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

• Java– Special form of for statement iterates on the elements of arrays and collections– form

for (<element-type> <var> : <collection>){…}

– e.g.

String [] list = {"Bob", "Carol", "Ted"};

for (String name : list)

System.out.println ("Name: " + name);– Note: there is no access to the element's index

Page 17: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

17Iteration on Data Structures: Scripting PLs

• Perl has a built-in iterator for arrays and hashes– e.g.,

foreach $name (@names){

print $name

}

• Iterator in JavaScript's for-in loop goes through indices, not through structure's elements– e.g.,

for (var index in names){

alert (name[index]);

}

Page 18: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

18Unconditional Branching - GOTOs

• Transfers control to a specific place in the program• Heated debates in 1960’s and 1970’s• Well-known mechanism:

– goto statement• Major concern: Readability• Some languages do not support goto statement

– e.g., Modula-2 and Java

• C# offers goto statement – can be used in switch statements

• Loop exit statements are restricted and camouflaged goto’s

• Generally considered BAD practice

Page 19: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

19Guarded Commands

• Suggested by Dijkstra

• Purpose: to support a new programming methodology supporting 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

Page 20: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

20Selection Guarded Command

• Formif <boolean-exp-1> -> <statement-1>

[] <boolean-exp-2> -> <statement-2>

...

[] <boolean-exp-n> -> <statement-n>

fi

• Semantics– When construct is reached

• Evaluate all Boolean expressions

• If one is true, choose it

• If more than one are true, choose one nondeterministically

– Execute the chosen expressions' statement

• If none are true, it is a runtime error

Page 21: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

21Selection Guarded Command (cont.)

true

true

Evaluate all Boolean expressions

All are false Run-time error

Exactly one is true

Randomly choose one of the true Boolean

expression

Execute associated statement

Page 22: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

22Loop Guarded Command

Formdo <boolean-exp-1> -> <statement-1>

[] <boolean-exp-2> -> <statement-2>

...

[] <boolean-exp-n> -> <statement-n>

od

• Semantics

– for each iteration• Evaluate all Boolean expressions

• If one is true, choose it

• If more than one are true, choose one nondeterministically

– Execute the chosen expressions' statement

• If none are true, exit loop

Page 23: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

23Loop Guarded Command (cont.)

True

False

True

False

Evaluate all Boolean expressions

All are false

Exactly one is true

Randomly choose one of the true

Boolean expressions

Execute the statement associated with the

chosen Boolean expression

Page 24: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

24Guarded Commands: Rationale

• There is an intimate connection between control statements and program verification

• Verification is

– Virtually impossible with goto statements

– Possible with only selection and logical pretest loops

– Relatively simple with only guarded commands

Page 25: 1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control

25Conclusion

• A variety of statement-level control structures

• Choice of control statements beyond selection and logical pretest loops is a trade-off between– Language size, and – Writability, readability, reliability

• Functional and logic programming languages have additional built-in control structures