+ All Categories
Home > Documents > Chapter 6: Control Flow

Chapter 6: Control Flow

Date post: 06-Jan-2016
Category:
Upload: iniko
View: 67 times
Download: 2 times
Share this document with a friend
Description:
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 - PowerPoint PPT Presentation
51
1 Chapter 6: Control Flow
Transcript

11

Chapter 6: Control Flow

22

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

33

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.

44

Control Flow Mechanisms

• Sequencing– Textual order, precedence and associativity in

expression

• Selection

• Iteration

• Procedural abstraction

• Recursion

• Concurrency

• Nondeterminacy

55

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

66

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

77

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

88

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

99

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

1010

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

1111

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

1212

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

1313

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

1414

Short-Circuited Conditions

if ((A>B) and (C>D)) or (E<>F) then

then-clause

else

else-clause

1515

Selection Efficient Case/Switch Example

Inefficient Code Inefficient Code GenerationGeneration

1616

Selection Efficient Case/Switch Example

Efficient Code Efficient Code GenerationGeneration

1717

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

1818

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

1919

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++; }

2020

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 = 110: ... i = i + 2 if i <= 10 goto 10

Notice:• Index variable ____ value is tested at _____• Step size and bounds ____ type _____• Body of the loop ____

2121

• 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!

Early (Fortran) Enumeration-controlled loops

2222

Iteration: For-loop

public void init(String args[]) {

/*

* print command line parameters

*/

for(int i=0; i<args.length; i++) {

System.out.println(args[i]);

} // end for

public void init(String args[]) {

/*

* print command line parameters

*/

for(int i=0; i<args.length; i++) {

System.out.println(args[i]);

} // end for

statementsstatements

true

false

forlooping

conditionconditionconditioncondition

initialize loop variable

initialize loop variable

increment loopvariable

increment loopvariable

for(initialize; test; increment) { // statements to execute}

for(initialize; test; increment) { // statements to execute}

2323

Iteration: For-loop

• The compiler checks for empty bounds.

• The compiler can generate optimized loop code.

2424

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

2525

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!

2626

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

2727

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

2828

• Clu allows any set-like abstract data type to provide an iterator

– E.g. integer iterator

Iteration: Iterators in Clu

2929

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 in Clu

3030

• Iterators can also be based on object-oriented design patterns

– Java’s Iterator interface» http://java.sun.com/docs/books/tutorial/collections/inter

faces/collection.html

• Enumeration-controlled loops evolved significantly since FORTRAN’s original for

Iteration: Iterators

3131

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

3232

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]=___

3333

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.'"

3434

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());}

3535

Java Enumeration

java.util.Enumeration

for (Enumeration e = v.elements(); e.hasMoreElements() ; ) {

Account account = (Account) e.nextElement(); System.out.println(account);}

3636

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 Iterator interface. In addition, Iterator adds an optional removeoperation, and has shorter method names.

New implementations should consider using Iterator in preference to Enumeration.

3737

Vector and ArrayList

Vector itemsOrdered = new Vector(100); // Vector with 100 slots ready for use 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

• Vector and ArrayList objects manage a collection of Java objects

Reference c[0]

[2][1]

ValueIndexrrr

Vector orArrayList

3838

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

invoicerefund

Example elements:sales

invoicerefund

c

Hashtable orHashMap

Index Refr

r

rrr

r

rr

3939

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.

4040

Java 1.4.2 java.util.Iterator

Iterator it = list.iterator();

while (it.hasNext()) {

Object val = it.next();

Account account = (Account)val; // casting is needed

account.update();

}

Iterators are created by the method iterator() provided by the corresponding container class.

4141

Java 1.4.2 and 1.5 Collections example

ArrayList list = new ArrayList();

list.add(0, new Account(...));

int amountDue = ((Account)list.get(0)).getAmountDue();

ArrayList<Account> list = new ArrayList<Account>();

list.add(0, new Account(...));

int amountDue = list.get(0).getAmountDue();

Using Java 1.4.2

Using the generified Collections library of Java 1.5

4242

Using the Generified Collections library of Java 1.5

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(0, 42);

int total = list.get(0);

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(0, new Integer(42));

int total = list.get(0).intValue();

Without autoboxing and auto-unboxing of primitive types

With autoboxing and auto-unboxing of primitive types

1

2

3

4

5

6

4343

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

}

}

4444

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

...

}

!

4545

Iteration

• Backward loops– Previous code assumed a positive step size

4646

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

4747

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

baaba

babba

baa

ba

if),gcd(

if),gcd(

if

),gcd(

4848

• Implementation using recursion is direct

baaba

babba

baa

ba

if),gcd(

if),gcd(

if

),gcd(

IterationIteration

RecursionRecursion

Recursion

4949

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

5050

• Nondeterministic constructs make choices between alternatives deliberately unspecified

• This mechanism is specially useful in concurrent programs

– Message-based concurrent languages

6.7 Nondeterminacy

5151

• This is a very practical matter– Event-driven programming is related to

nondeterminacy» See events and listeners in Java» http://java.sun.com/docs/books/tutorial/uiswing/overvie

w/event.html– Non-blocking IO is related to nondeterminacy

» See the latest addition to Java (1.4): Channels and Selectors

» http://java.sun.com/j2se/1.4/docs/guide/nio/index.html

6.7 Nondeterminacy


Recommended