C OMP 110 L OOPS Instructor: Jason Carter. 2 L OOPS More loops Off-by-one errors Infinite loops Nested Loops Animations Concurrency Synchronized methods.

Slides:



Advertisements
Similar presentations
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Advertisements

Computer Science II Recursion Professor: Evan Korth New York University.
Computer Science 1620 Loops.
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Loops More loops Off-by-one errors Infinite loops Nested Loops.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
C OMP 401 A NIMATION L OOPS Instructor: Prasun Dewan.
C OMP 110 L OOPS A DVANCED Instructor: Prasun Dewan.
C OMP 110/401 C OMPOSITE A NNOTATIONS Instructor: Prasun Dewan.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Iteration Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Advanced Arithmetic, Conditionals, and Loops INFSY 535.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
C OMP 401 A NIMATION : MVC Instructor: Prasun Dewan.
C OMP 401 U SER -I NTERFACE VS. M AIN T HREADS Instructor: Prasun Dewan.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Computer C programming Chapter 3. CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement.
UCT Department of Computer Science Computer Science 1015F Iteration
Chapter 4 Repetition Statements (loops)
Loop Structures.
Java Software Structures: John Lewis & Joseph Chase
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Outline Altering flow of control Boolean expressions
Recitation 12 November 18, 2011.
Review of Previous Lesson
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Review for Midterm 3.
Chapter 4: Loops and Iteration
Presentation transcript:

C OMP 110 L OOPS Instructor: Jason Carter

2 L OOPS More loops Off-by-one errors Infinite loops Nested Loops Animations Concurrency Synchronized methods Property changes

3 M ULTIPLYING N UMBERS int product = 1; int nextNum = Console.readInt(); while (nextNum >= 0) { product = product* nextNum; nextNum = Console.readInt(); } print (product);

4 C UMULATIVE A SSIGNMENT int product = 1; int nextNum = Console.readInt(); while (nextNum >= 0) { product *= nextNum; nextNum = Console.readInt(); } print (product); product *= nextNum;product = product * nextNum; = sum += numsum = sum+num

5 M ULTIPLYING P OSITIVE N UMBERS int product = 1; int nextNum = Console.readInt(); while (nextNum >= 0) { product *= nextNum; nextNum = Console.readInt(); } print(product);

6 M ULTIPLYING N N UMBERS (E DIT ) int product = 1; int nextNum = Console.readInt(); while (nextNum >= 0) { product *= nextNum; nextNum = Console.readInt(); } print(product);

7 M ULTIPLYING N N UMBERS int product = 1; int nextNum = Console.readInt(); while (nextNum >= 0) { product *= nextNum; nextNum = Console.readInt(); } print (product); int listLength = readListLength(); int counter = 0; int nextNum; int product = 1; while (counter < listLength) { counter += 1; nextNum = readNextNumber(); product *= nextNum; } print (product);

8 M ULTIPLYING F IRST N N UMBERS : N! (E DIT ) 1*2*3*4*…*nFactorial(n) = n!

9 M ULTIPLYING F IRST N N UMBERS : N! int product = 1; int n = 2; int counter = 0; while (counter < n) { product *= counter; counter += 1; } System.out.println (product); 1*2*3*4*…*n 1*0*1

10 M ULTIPLYING F IRST N N UMBERS : N! int product = 1; int n = ???; int counter = 0; while (counter < n) { product *= counter; counter += 1; } System.out.println (product); 1*2*3*4*…*nOff by one 1*0*1*2*3*4*…*n-1

11 M ULTIPLYING F IRST N N UMBERS : N! int product = 1; int n = ???; int counter = 1; while (counter < n) { product *= counter; counter += 1; } System.out.println (product); 1*2*3*4*…*nOff by one 1*1*2*3*4*…*n-1

12 M ULTIPLYING F IRST N N UMBERS : N! int product = 1; int n = ???; int counter = 1; while (counter <= n) { product *= counter; counter += 1; } System.out.println (product); 1*2*3*4*…*n 1*1*2*3*4*…*n-1*n

13 B ETTER N AME int product = 1; int n = ???; int nextMultiplier = 1; while (nextMultiplier <= n) { product *= nextMultiplier; nextMultiplier += 1; } System.out.println (product); 1*2*3*4*…*n 1*1*2*3*4*…*n-1*n

14 B ETTER N AME int product = 1; int n = ???; int nextMultiplier = 0; while (nextMultiplier <= n) { product *= nextMultiplier; nextMultiplier += 1; } System.out.println (product); 1*2*3*4*…*n Easier to spot off-by-one errors 1*1*2*3*4*…*n-1*n

15 I NCREMENTING C OUNTER B EFORE O PERATION int product = 1; int n = ???; int prevMultiplier = 0; while (prevMultiplier <= n) { prevMultiplier += 1; product *= prevMultiplier; } System.out.println (product); 1*2*3*4*…*n 1*1*2*3*4*…*n-1*n*n+1 Off by one

16 I NCREMENTING C OUNTER B EFORE O PERATION int product = 1; int n = ???; int prevMultiplier = 0; while (prevMultiplier < n) { prevMultiplier += 1; product *= prevMultiplier; } System.out.println (product); 1*2*3*4*…*n 1*1*2*3*4*…*n-1*n

17 C HECKING OF N ON E QUALITY int product = 1; int n = ???; int prevMultiplier = 0; while (prevMultiplier != n) { prevMultiplier += 1; product *= prevMultiplier; } System.out.println (product); 1*2*3*4*…*n

18 C HECKING OF N ON E QUALITY int product = 1; int n = -5; int prevMultiplier = 0; while (prevMultiplier != n) { prevMultiplier += 1; product *= prevMultiplier; } System.out.println (product); 1*2*3*4*…*n

19 C HECKING OF N ON E QUALITY int product = 1; int n = -5; int prevMultiplier = 0; while (prevMultiplier != n) { prevMultiplier += 1; product *= prevMultiplier; } System.out.println (product); 1*2*3*4*…*n -5*-4*-3*-2*-1*0*1*2... Infinite loop

20 C OUNTER N OT C HANGED int product = 1; int n = ???; int prevMultiplier = 0; while (prevMultiplier < n) { product *= prevMultiplier; } System.out.println (product); 1*2*3*4*…*n 1*0*0*0*… Infinite loop

21 C OUNTER C HANGED IN THE W RONG D IRECTION int product = 1; int n = ???; int prevMultiplier = 0; while (prevMultiplier < n) { prevMultiplier -= 1; product *= prevMultiplier; } System.out.println (product); 1*2*3*4*…*n 1*0*-1*-2*… Infinite loop

22 G UARDING A GAINST I NFINITE L OOPS Update variable(s) in loop expression Expression must converge to false

23 D ECREMENTING S OLUTION int product = 1; while (n > 0) { product *= n; n -= 1; } System.out.println(product); 1*2*3*4*…*n 1*n*n-1*n-2*..1 Backwards multiplication

24 D ECREMENTING S OLUTION int product = 1; while (n > 0) { product *= n; n--; } System.out.println(product); n--  n = n - 1 n++  n = n + 1

25 C OUNTER -C ONTROLLED VS. E VENT -C ONTROLLED int product = 1; int nextNum = Console.readInt(); while (nextNum >= 0) { product *= nextNum; nextNum = Console.readInt(); } print (product); int product = 1; int n = readNumElements(); int counter = 0; while (counter < n) { int nextNum = readNum(); product *= nextNum; counter += 1; } Event-controlled Counter-controlled

26 C OUNTER -C ONTROLLED VS. E VENT -C ONTROLLED Number of loop iterations (executions of loop body) known before loop executed initialize counter to some value increment/decrement counter by fixed step beginning/end of body exit when counter reaches limit Limit not known before loop starts Test one more events (e.g. reading of input) occurring while loop executes Terminate when events make loop condition false

27 C OUNTER -C ONTROLLED VS. E VENT -C ONTROLLED Counting until 10 in Hide & Seek Searching for others in Hide & Seek Grading Comp14 exams Fishing for the right answer from students Counting the days until it is vacation Counting # of candies in a jar Counter-controlled Event-controlled Counter-controlled Event-controlled & counter-controlled Counter-controlled Event-controlled

28 F ACTORIAL L IST (E DIT ) int n = ???; int product = 1; while (n > 0) { product *= n; n -= 1; } return product;

29 F ACTORIAL L IST public static int factorial ( int n) { int product = 1; while (n > 0) { product *= n; n -= 1; } return product; } public static void main (String[] args) { int newVal = Console.readInt(); while (newVal >= 0) { System.out.println(“factorial =“ + factorial(newVal)); newVal = Console.readInt(); }

30 R EMOVING C ODE D UPLICATION (E DIT ) public static void main (String[] args) { int newVal = Console.readInt(); while (newVal >= 0) { System.out.println(“factorial =“ + factorial(newVal)); newVal = Console.readInt(); } public static int factorial ( int n) { int product = 1; while (n > 0) { product *= n; n -= 1; } return product; }

31 B REAK S TATEMENT public static void main (String[] args) { while ( true ) { // loop condition never false int newVal = Console.readInt(); if (newVal < 0) { break ; } System.out.println(“factorial =“ + factorial(newVal); } public static int factorial ( int n) { int product = 1; while (n > 0) { product *= n; n -= 1; } return product; }

32 A NIMATED S HUTTLE

33 A NIMATED S HUTTLE

34 A NIMATED S HUTTLE

35 A NIMATED S HUTTLE

36 A NIMATED S HUTTLE

37 A NIMATED S HUTTLE

38 A NIMATED S HUTTLE

39 A NIMATED S HUTTLE

40 A NIMATED S HUTTLE

41 A NIMATED S HUTTLE

42 A NIMATED S HUTTLE

43 A NIMATE F ROM O RIGIN S EMANTICS (E DIT ) Basic Idea: Should animate from origin to current location

44 A NIMATE F ROM O RIGIN S EMANTICS Basic Idea: Should animate from origin to current location Should move to origin Should animate first in Y direction to current Y Next should animate in X direction to current X

45 A NIMATING TO A D ESTINATION L OCATION 1. Should move a constant distance in straight line to destination 2. Go back to 1 if location not reached

46 A NIMATING TO A D ESTINATION L OCATION 1. Should move a constant distance in straight line to destination 2. Should pause for time defined by animationPauseTime property 3. Go back to 1 if location not reached

47 P AUSING P ROGRAM ASSIGNMENT_TIME different on different computers! Unnecessarily using the CPU (Busy Waiting) Need the OS to suspend to put to sleep program for pause time void sleep ( int pauseTime) { int numberOfAssignments = pauseTime; //ASSIGNMENT_TIME; for ( int i = 0; i < numberOfAssignments; i++) { int dummy = 0; // nonsense assignment }

48 P AUSING P ROGRAM void sleep( int pauseTime) { try { // OS suspends program for pauseTime Thread.sleep(pauseTime); } catch (Exception e) { // program may be forcibly interrupted while sleeping e.printStackTrace(); }; }

49 P AUSE T IME P ROPERTY (E DIT )

50 P AUSE T IME P ROPERTY int animationPauseTime; public int getAnimationPauseTime() { return animationPauseTime; } public void setAnimationPauseTime( int newVal) { animationPauseTime = newVal; }

51 A NIMATING C ODE (E DIT ) public void animateFromOrigin() { }

52 A NIMATING C ODE public synchronized void animateFromOrigin() { int curX = 0; int curY = 0; setLabelX(windowX(nextX)); setLabelY(windowY(nextY)); // make sure we don’t go past final Y position while (curY < getShuttleY()) { sleep(getAnimationPauseTime()); curY += ANIMATION_STEP; setLabelY(windowY(curY)); } // move to final Y position setLabelY(windowY(getShuttleY())); while (curX < getShuttleX()) { sleep(getAnimationPauseTime()); curX += ANIMATION_STEP; setLabelX(windowX(curX)); } setLabelX(windowX(getShuttleX())); }

53 W HY S YNCHRONIZED ? For a non-synchronized method ObjectEditor waits for invoked method to finish before taking the next step of updating the display If animateFromOrigin was non-synchronized would only see the final position menu is frozen until method finishes, cannot execute another activity

54 A NIMATION R EQUIRES C ONCURRENT T HREADS During animation two interleaved activities must take place animateFromOrigin moves current X and Y Object editor displays intermediate X and Y positions ObjectEditor cannot wait for method to finish It must create a new thread or activity for animateFromOrigin The keyword synchronized tells ObjectEditor to do so

55 C ONCURRENCY In the case of synchronized method, we can ask ObjectEditor to invoke another method while previous one is executing

56 C ONCURRENCY Can have two animateFromOrigin executed concurrently by two different threads (Thread-3 and Thread-4)! Other threads? UI processing Garbage collection …

57 C ONCURRENCY Can have two animateFromOrigin executed concurrently by two different threads (Thread-3 and Thread-4)! Second one can interfere with first one Can reset label position

58 C ONCURRENCY The keyword synchronized tells Java that only one thread should execute the method at one time Thread-4 is suspended at first statement until Thread-3 completes method Cannot reset shuttle location set by Thread-3

59 T HE R OLE OF S YNCHRONIZED The keyword synchronized tells ObjectEditor that a new thread should be created for executing the method. Java that only one thread should execute the method at one time Extra thread needed and keyword needed even if we don’t use ObjectEditor and create our own display- engine for animating So requiring animating methods to be synchronized is not a special ObjectEditor requirement

60 W HEN IS D ISPLAY U PDATED Normally ObjectEditor updates display at the end of the execution of each method Does not work for animating method Need to update after each change Must explicitly tell ObjectEditor that change occurred. How?

61 O BJECT E DITOR O BSERVER P ROTOCOL ObjectEditor implements the standard PropertyChangeListener interface public interface PropertyChangeListener { public void propertyChange(PropertyChangeEvent arg) } public class ObjectEditor implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent arg) {... }

62 O BJECT E DITOR O BSERVER P ROTOCOL If the class of a displayed object defines the standard method: public void addPropertyChangeListener (PropertyChangeListener l) ObjectEditor calls the method to register itself as an observer Method should store a reference to ObjectEditor and other observers public class ACartesianPoint implements Point { … public void addPropertyChangeListener(PropertyChangeListener l) { observers.addElement(l); }

63 O BJECT E DITOR O BSERVER P ROTOCOL A property changing method can now call the propertyChange(PropertyChangeEvent arg) defined by PropertyChangeListener to inform ObjectEditor and other observers about change public void notifyAllListeners(PropertyChangeEvent e) { for ( int index = 0; index++; index < observers.size() { observers.elementAt(i).propertyChange(e); } public void setX ( int newVal) { int oldVal = x; x = newVal; notifyAllListeners(new PropertyChangeEvent( this, “x”, oldVal, newVal); }

64 A PPLYING T HESE C ONCEPTS How should the class AnAnimatingShuttleLocation be changed?

65 O BJECT E DITOR O BSERVER P ROTOCOL The implementation of this method in ObjectEditor updates the display public class ObjectEditor implements java.beans.PropertyChangeListener { public void propertyChange (PropertyChangeEvent arg) { // update display of property arg.getPropertyName() // to show arg.getNewValue() … }

66 A NIMATING C ODE public synchronized void animateFromOrigin() { int curX = 0; int curY = 0; setLabelX(windowX(nextX)); setLabelY(windowY(nextY)); // make sure we don’t go past final Y position while (curY < getShuttleY()) { sleep(getAnimationPauseTime()); curY += ANIMATION_STEP; setLabelY(windowY(curY)); } // move to final Y position setLabelY(windowY(getShuttleY())); while (curX < getShuttleX()) { sleep(getAnimationPauseTime()); curX += ANIMATION_STEP; setLabelX(windowX(curX)); } setLabelX(windowX(getShuttleX())); }

67 A NIMATING C ODE void setLabelX( int x) { Point oldLocation = shuttleLabel.getLocation(); Point newLocation = new ACartesianPoint(x, oldLocation.getY()); shuttleLabel.setLocation(newLocation); }

68 C LASS AL ABEL public void setLocation(Point newVal) { location = newVal; }

69 M AKE AL ABEL A M ODEL public class ALabel implements Label { PropertyChangeListenerHistory observers = new APropertyChangeListenerHistory(); public void addPropertyChangeListener(PropertyChangeListener l) { observers.addElement(l); } public void notifyAllListeners(PropertyChangeEvent e) { for ( int index = 0; index++; index < observers.size() { observers.elementAt(i).propertyChange(e); } Property-independent code

70 C LASS AL ABEL (E DIT ) public void setLocation(Point newVal) { location = newVal; }

71 C LASS AL ABEL public void setLocation(Point newVal) { Point oldVal = location; location = newVal; notifyAllListeners( new PropertyChangeEvent( this, “Location”, oldVal, newVal); }

72 A NIMATION S TEPS Animation consists of one or more animation steps An animation step updates one or more animating graphical properties such as size, location, and icon of one or more graphical objects and then pauses execution

73 P AUSING E XECUTION Execution can be paused using busy waiting or a sleep call provided by the operating system Busy waiting has the problem that it is platform- specific and does not allow other activity to proceed while the animation is paused Therefore using the sleep call is preferable

74 I NCREMENTAL U PDATES After each animation step, all displays of the animation must be updated The observable-observer concept can be used to ensure these updates are made for each graphical property changed by the animation, the class of the property should allow observers to be registered and the setter of the property informs the observers about the update ObjectEditor requires the JavaBeans observer- observer approach based around the PropertyChangeListener interface

75 T HREADS An animating method should be executed in a separate thread as otherwise the user-interface thread will wait for it to finish execution before performing any screen update This means that it is possible to start multiple executions of the method concurrently We should use the keyword synchronized in the declaration of the method to ensure that is it is executed serially by the thread The keyword synchronized also tells ObjectEditor to start a new thread to execute the method

76 A NIMATING VS. U PDATING C LASSES In general, a method that performs the animation steps and a method that changes the value of some animating property may be in different classes: AnAnimatingShuutleLocation ALabel