1 / 25

Iterative Statements

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 How is iteration controlled ? boolean expression or counter? Where is the control mechanism ?

rowland
Download Presentation

Iterative Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 • How is iteration controlled ? • boolean expression or counter? • Where is the control mechanism ? • pre or post?

  2. Counter-Controlled Loops • Counting loop variable • the variable • a means of specifying the initialandterminal values • step-sizevalues • Design Issues • What are the type and scope of the loop variable? • What is the value of the loop variable at loop termination? • Is it legal to change the loop variable or loop parameters in the loop body? • if so, does the change affect loop control? • Should the loop parameters be evaluated only once, orevery iteration?

  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: • Loop variable must be INTEGER • Loop variable has its last value after loop termination • Loop variable cannot be changed in the loop • Loop parameters are evaluated only once • 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. Iterative Statements: Pascal's for • Pascal’s for statement for variable := initial (to|downto) final do statement • Design choices: • Loop variable must be an ordinal typeof usual scope • After normal termination, loop variable is undefined • The loop variable cannot be changed in the loop; • Loop parameters can be changed • Loop parameters are evaluated just once • Changing them does not affect loop control • Endless loops are avoided

  5. Iterative Statements: Ada • Ada forvar in [reverse]discrete_rangeloop ... end loop • A discrete_rangeis 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. 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 2nd expression is evaluated before each iteration • The 3rd expression is evaluated before each iteration

  7. Iterative Statements: C++ and Java • C++ differs from C in that • The control expression can also be Boolean • 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. 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: • while (ctrl_expr)loop_body • doloop_bodywhile (ctrl_expr)

  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. 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. 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 • Is the condition executed before exiting? • Can control exit more than the innermost loop?

  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 labeledbreak statement transfers control to the label • Also, a return statement exits loops • it exits a subprogram (see later)

  13. Lisp – 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

  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. Lisp Specialized Iteration • Iterate over integers from 0 to limit: (dotimes (<var> <limit> <return-value>) <forms>*) • Iterate over elements of a list: (dolist (<var> <list> <return-value>) <forms>*)

  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 (<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

  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. 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. 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. Selection Guarded Command • Form if <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

  21. Selection Guarded Command (cont.) Evaluate all Boolean expressions true All are false Run-time error true Execute associated statement Exactly one is true Randomly choose one of the true Boolean expression

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

  23. Loop Guarded Command (cont.) Evaluate all Boolean expressions True All are false Execute the statement associated with the chosen Boolean expression False True Exactly one is true False Randomly choose one of the true Boolean expressions

  24. Guarded Commands: Rationale • There is an intimate connection between control statements and program verification • Verification is • Virtually impossiblewith goto statements • Possiblewith only selection and logical pretest loops • Relatively simple withonly guarded commands

  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

More Related