Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control."— Presentation transcript:

1 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?

2 2 Counter-Controlled Loops Counting loop variable –the variable –a means of specifying the initial and terminal values –step-size values Design Issues 1.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?

3 3 Iterative Statements: FORTRAN's DO FORTRAN 90 syntax DO 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

4 4 Iterative Statements: Pascal's for Pascal’s for statement for 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 once 1.Changing them does not affect loop control Endless loops are avoided

5 5 Iterative Statements: Ada Ada for 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

6 6 Iterative Statements: C's for C’s for statement for ([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 2 nd expression is evaluated before each iteration The 3 rd expression is evaluated before each iteration

7 7 Iterative Statements: C++ and Java C++ differs from C in that 1.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?!

8 8 Logically-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)

9 9 Logically-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

10 10 Logically-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

11 11 User-Located Loop Control Convenience for control to skip part of loop body Simple design for single loops –e.g., break Design issues for nested loops 1.Is the condition executed before exiting? 2.Can control exit more than the innermost loop?

12 12 User-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)

13 13 Lisp – General Iteration with do The do macro is CL’s fundamental iteration operator (do ((var-1 value-1 next-1)*... ) ( * ) ) First argument is –a list of variable specifications –form: (var initial-value update) The second argument is –a list containing one or more expressions ( *) –The 1 st 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

14 14 Iteration 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)) {...}

15 15 Lisp Specialized Iteration 1.Iterate over integers from 0 to limit : (dotimes ( ) *) 2.Iterate over elements of a list: (dolist ( ) *)

16 16 Iteration 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 ( : ){ … } –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

17 17 Iteration 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]); }

18 18 Unconditional 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

19 19 Guarded 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

20 20 Selection Guarded Command Form if -> [] ->... [] -> 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

21 21 Selection Guarded Command (cont.) 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

22 22 Loop Guarded Command Form do -> [] ->... [] -> 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

23 23 Loop 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

24 24 Guarded 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

25 25 Conclusion 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


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

Similar presentations


Ads by Google