550 likes | 1.05k Vues
Chapter 6: Control Flow. Chapter 6: Control Flow. 6.1 Expression Evaluation 6.2 Structured and Unstructured Flow 6.3 Sequencing 6.4 Selection 6.5 Iteration 6.6 Recursion 6.7 Non-determinacy. Control Flow. Control flow refers to the order in which a program executes
E N D
Chapter 6: Control Flow 6.1 Expression Evaluation 6.2 Structured and Unstructured Flow 6.3 Sequencing 6.4 Selection 6.5 Iteration 6.6 Recursion 6.7 Non-determinacy
Control Flow • Control flow refers to the order in which a program executes • This is fundamental in the imperative programming paradigm • E.g. Java, C++, Pascal, Fortran, Ada, etc.
Control Flow Mechanisms • Sequencing • Textual order, precedence and associativity in expression • Selection • Iteration • Procedural abstraction • Recursion • Concurrency • Nondeterminacy
Chapter 6: Control Flow 6.1 Expression Evaluation 6.2 Structured and Unstructured Flow 6.3 Sequencing 6.4 Selection 6.5 Iteration 6.6 Recursion 6.7 Non-determinacy
Unstructured FlowThe GOTO Statement • Control flow in assembly languages is achieved by means of conditional jumps and unconditional jumps (or branches) • E.g. JMP 30 … 30: ADD r1, #3 • 30 is an assembly-level label • Higher level languages had similar statement: goto • E.g. In FORTRAN, If A .lt. B goto 10 … 10: … • 10 is a statement label
Unstructured FlowThe GOTO Statement • Goto is considered evil since the 70s • It potentially makes programs extremely convoluted • Spaghetti code • Code may be difficult to debug and even more difficult to read • In 1967, Dijkstra’s published an classic article, GoTo Considered Harmful, that pointed out the dangers of the goto statement in large programs • The larger the program, the worse the impact of goto statements
Structured Flow • Structured flow eliminates goto • Nested constructs (blocks) provide the same expressive power • Any program can be expressed using sequencing, selection and iteration • This was proved in a 1964 paper by Bohm & Jacopini • However, there is a small number of cases in which unstructured flow is still more convenient • Modern structured languages like Java have addressed these cases in an structured manner
Structured FlowSpecial Cases • Break and continue • Java’s branching statements • http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html • Early subroutine returns • Java’s return statements • http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html • Exceptions and Errors • Java’s exception handling • http://java.sun.com/docs/books/tutorial/java/nutsandbolts/exception.html
Chapter 6: Control Flow 6.1 Expression Evaluation 6.2 Structured and Unstructured Flow 6.3 Sequencing 6.4 Selection 6.5 Iteration 6.6 Recursion 6.7 Non-determinacy
Sequencing • Sequencing is central to imperative programming languages • Sequencing of statements is usually defined by textual orders • Enclosed sequences of statements are called compound statements or blocks • E.g. begin … end, { … } • Declarations (e.g. variable types) may also be part of a code block
Chapter 6: Control Flow 6.1 Expression Evaluation 6.2 Structured and Unstructured Flow 6.3 Sequencing 6.4 Selection 6.5 Iteration 6.6 Recursion 6.7 Non-determinacy
Selection • If/Then/Else statement • Case/Switch statement • The motivation for this statement is not purely esthetical • In some cases, switch statements are faster than nested if/then/else • The argument of the conditional must be a discrete value so that selection can be accomplished using an array indexed by the values (rather than checking the cases sequentially) • The break statement in C/C++/Java makes code generation even more efficient in some case
Short-Circuited Conditions if ((A>B) and (C>D)) or (E<>F) then then-clause else else-clause
SelectionEfficient Case/Switch Example Inefficient Code Generation
SelectionEfficient Case/Switch Example Efficient Code Generation
Chapter 6: Control Flow 6.1 Expression Evaluation 6.2 Structured and Unstructured Flow 6.3 Sequencing 6.4 Selection 6.5 Iteration 6.6 Recursion 6.7 Non-determinacy
Iteration and Recursion • Iteration and recursion are the two control flow mechanism allow a computer to perform the same set of operations repeatedly. • They make computers useful • Go beyond the power of deterministic finite automata • Imperative languages mainly rely on iteration • Functional languages make more use of recursion
Iteration • Iteration usually takes the form of loops • There are two principal varieties • Enumeration-controlled loops • E.g. for (int i = 0; i <= 10; i++) { … } • Logically controlled loops • E.g. int i = 0; while (i <= 10) { … i++; }
Early Enumeration-Controlled Looping Syntax Let's start with Fortran for loop from 1954 (still available in F90 today) do 10 i = 1, 10, 2 ... 10 continue i = 1 10: ... i = i + 2 if i <= 10 goto 10 • Notice: • Index variable ____ value is tested at _____ • Step size and bounds ____ type _____ • Body of the loop ____
Early (Fortran) Enumeration-controlled loops • Problems: • Loop boundaries must be integer • Expressions are not allowed • The index variable can change within the body of the loop • Goto statements may jump in and out of the loop • The value of i after the termination of the loop is implementation dependent • The test of the loop takes place at the end, so the body is executed at least once • Even if the lower bound is larger than the upper bound!
for looping initialize loop variable condition false true statements increment loop variable Iteration: For-loop for(initialize; test; increment) { // statements to execute } public void init(String args[]) { /* * print command line parameters */ for(int i=0; i<args.length; i++) { System.out.println(args[i]); } // end for
Iteration: For-loop • The compiler checks for empty bounds. • The compiler can generate optimized loop code.
Iteration: Access to Index Outside the Loop • The value of the index variable at the end of loop is undefined in several languages • E.g. Fortran, Pascal • Compilers can fix this, but… • Generating slower code
Iteration: Access to Index Outside the Loop • The value of the index after the loop completes may not be valid • E.g. var c: ‘a’..’z’; … for c:= ‘a’ to ‘z’ do begin … end; (* what comes after ‘z’? *) • In summary, even the simplest type of loop requires a good design • You will use language with poorly designed statements!
Iteration: Iterators • Iterators generalize enumeration-controlled loops • In the previous examples, the iteration was always over the elements of an arithmetic sequence • Iterators are used to enumerate the elements of any well-defined set • An iterator knows two things: How to get the next value from the collection When no more elements are available
Iteration: Iterators in Clu • Iterators are used to enumerate the elements of any well-defined set • E.g. In Clu, for i in from_to_by(first, last, step) do … end • Notice some similarity to Perl’s foreach statement
Iteration: Iterators in Clu • Clu allows any set-like abstract data type to provide an iterator • E.g. integer iterator
Iteration: Iterators in Clu Iterators in CLU look like ordinary procedures. However, they produce a sequence of values, rather than just one. Each time an iterator executes a yield <value> statement, the iterator returns <value>. When it is called again, the iterator picks up its computation after the yield, so it can compute thenext value to return. In CLU, when the iterator finishes, the controlling for loop inwhich it is being called also terminates.
Iteration: Iterators • Iterators can also be based on object-oriented design patterns • Java’s Iterator interface • http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html • Enumeration-controlled loops evolved significantly since FORTRAN’s original for
Java Looping Evolution • Java 1.4 for loop • Java 1.4 java.util.Enumeration • Java 1.4 java.util.Iterator • Java 1.5 generified Iterator • Java 1.5 enhanced for loop
Java 1.4 for loops public static void main(String[] args) { int[] array = { 32, 87, 13, 89, 12, 27 }; for (int i = 0; i < array.length; i++) { array[i] += 1; System.out.println(array[i] + " "); } } // end of main() array.length=___ array[0]=___ array[array.length]=___
Java Collection Framework "Our main design goal was to produce an API that was reasonably small, both in size, and (more importantly) in 'conceptual weight.'"
Java Enumeration java.util.Enumeration An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series. For example, to print all elements of a vector v: for (Enumeration e = v.elements(); e.hasMoreElements() ; ) { System.out.println(e.nextElement());}
Java Enumeration java.util.Enumeration for (Enumeration e = v.elements(); e.hasMoreElements() ; ) { Account account = (Account) e.nextElement(); System.out.println(account);}
Java 1.4.2 java.util.Enumeration Methods are provided to enumerate through the elements of a vector, the keys of a hashtable, and the values in a hashtable. NOTE: The functionality of this interface is duplicated by the Iteratorinterface. In addition, Iterator adds an optional removeoperation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.
Vector or ArrayList c Reference Index [0] Value r r [1] [2] … r Vector and ArrayList • Vector and ArrayList objects manage a collection of Java objects Vector itemsOrdered = new Vector(100); // Vector with 100 slots ready for use • Variable number of items in the collection • The collection items may be initialized or uninitialized • Items can be different types of objects
Hashtable or HashMap c Index Ref r r r r r r r r Hashtable and HashMap Overview • Hashtable and HashMap classes are collections of different objects, indexed by a key object, eg: an order number stored in a String object. • Elements may be inserted, retrieved, overwritten or removed,by key. Example elements: sales invoice refund
Java 1.4.2 java.util.Iterator • java.util.Iterator - An iterator over a collection. • Iterator takes the place of Enumeration in the Java collections framework. • Iterators differ from enumerations in two ways: • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. • Method names have been improved.
Java 1.4.2 java.util.Iterator Iterators are created by the method iterator() provided by the corresponding container class. Iterator it = list.iterator(); while (it.hasNext()) { Object val = it.next(); Account account = (Account)val; // casting is needed account.update(); }
Java 1.4.2 and 1.5 Collections example Using Java 1.4.2 ArrayList list = new ArrayList();list.add(0, new Account(...)); int amountDue = ((Account)list.get(0)).getAmountDue(); Using the generified Collections library of Java 1.5 ArrayList<Account> list = new ArrayList<Account>();list.add(0, new Account(...));int amountDue = list.get(0).getAmountDue();
Using the Generified Collections library of Java 1.5 Without autoboxing and auto-unboxing of primitive types ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, new Integer(42));int total = list.get(0).intValue(); 1 2 3 With autoboxing and auto-unboxing of primitive types ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, 42);int total = list.get(0); 4 5 6
Java 1.4 and 1.5 Iteration Example static void expurgate(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) { String s = (String) i.next(); if(s.length() == 4) i.remove(); } } static void expurgate(Collection<String> c) { for (Iterator<String> i = c.iterator(); i.hasNext(); ) if (i.next().length() == 4) i.remove(); } }
Java 1.5 Iterator and Java 1.5 For Loop ArrayList<Integer> list = new ArrayList<Integer>();for (Iterator i = list.iterator(); i.hasNext(); ) { Integer value = (Integer) i.next(); ... value.compareTo(...)...} ArrayList<Integer> list = new ArrayList<Integer>(); for (Integer i : list) { ...i.compareTo(...)... ... } !
Iteration • Backward loops • Previous code assumed a positive step size
Chapter 6: Control Flow 6.1 Expression Evaluation 6.2 Structured and Unstructured Flow 6.3 Sequencing 6.4 Selection 6.5 Iteration 6.6 Recursion 6.7 Nondeterminacy
Recursion • Recursion requires no special syntax • Recursion and logically-controlled iteration are equally powerful • Example • Compute the greatest common divisor • It can be defined as a recurrence: for a, b positive integers
Recursion • Implementation using recursion is direct Recursion Iteration
Chapter 6: Control Flow 6.1 Expression Evaluation 6.2 Structured and Unstructured Flow 6.3 Sequencing 6.4 Selection 6.5 Iteration 6.6 Recursion 6.7 Nondeterminacy
6.7 Nondeterminacy • Nondeterministic constructs make choices between alternatives deliberately unspecified • This mechanism is specially useful in concurrent programs • Message-based concurrent languages